我试图在 JFrame 的文本区域中获取用户的输入,然后在另一个类中使用它,但它总是返回 null。如果我对变量 encryptString 进行硬编码,它将显示,但当我将其保存为加密操作监听器时不会显示
JFrame加密文件
public class Encrypt extends JFrame {
public String encryptString ;
/**
* Creates new form NewJFrame1
*/
public Encrypt() {
initComponents();
}
/**
* Run on encryption button press
*/
private void encryptionButtonActionPerformed(java.awt.event.ActionEvent evt) {
//windowClosed();
run();
encryptString = textForEncryption.getText();
textForEncryption.setText(encryptString +"hey");
Display display = new Display();
display.setVisible(true);
//close();
}
我尝试访问的 AES 文件。
public class AES {
public static void run(){
Encrypt e = new Encrypt();
String strDataToEncrypt = e.encryptString;
String strCipherText;
String strDecryptedText;
System.out.println(strDataToEncrypt);
System.out.println(e.encryptString);
}
最佳答案
您的代码使用 AES 方法向后查看,创建一个加密 GUI,并在用户有机会对其执行任何操作之前立即从 GUI 中提取公共(public)(并且可能空)字符串。了解 AES 创建的 GUI 可能与向用户显示的 GUI 不同。
不,我认为 GUI 或更好的控件(其 ActionListeners)应该有一个非 GUI 加密对象,该对象从 ActionListener 的 actionPerformed 方法中获取相关字符串,然后让加密类执行其操作。
类似这样的半伪代码:
GUI 类
public class Gui {
public Gui() {
myButton.addActionListener(new ButtonListener(this));
}
}
控制类
public class ButtonListener implements ActionListener {
private Gui gui;
public ButtonListener(Gui gui)
this.gui = gui;
}
public void actionPerformed(ActionEvent evt) {
String preEncryptString = gui.getPreEncryptString(); // get from text component
NonGuiEncryption encryption = new NonGuiEncryption(preEncryptString);
// the code below might need to be done in a background thread
// depending on how long it takes to run
String encryptString = encryption.doEncryption();
// the code below must be run on the EDT, but after the code above completes
gui.putEncriptString(encryyptString);
}
}
关于java - 获取变量以在新方法 Java 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660886/