我在ActionListener事件中遇到变量问题。我正在编写一个程序,通过使用用户定义的密码创建和加密/解密包含文件中文本的格式化字符串,然后将其写入文件来加密和解密文件。我的问题发生在我的ActionListeners中。这是我的代码:
private void buttonEncryptActionPerformed(java.awt.event.ActionEvent evt) {
int retVal = selectFile.showOpenDialog(null);
if (retVal == selectFile.APPROVE_OPTION) {
java.io.File theFile = selectFile.getSelectedFile();
dialogEncryptPassword.setVisible(true);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(theFile));
} catch (FileNotFoundException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
}
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} catch (IOException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
br.close();
} catch (IOException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private void buttonOKEncryptActionPerformed(java.awt.event.ActionEvent evt) {
String password = passwordEncrypt.getText();
try {
DESKeySpec key = new DESKeySpec(password.getBytes());
} catch (InvalidKeyException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
}
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
}
CryptString crypt = new CryptString(KeyFactory.generateSecret(key));
String encryptedString = crypt.encryptBase64(everything);
dialogEncryptPassword.dispose();
}
我在两条线上找不到符号:
CryptString crypt = new CryptString(KeyFactory.generateSecret(key));
String encryptedString = crypt.encryptBase64(everything);
这是因为字符串"所有"在之前的ActionListener事件中定义,我不知道如何访问在其他事件中定义的变量。我不知道为什么它无法找到符号" key",因为它是在同一事件中声明的。我的一些代码可能不正确,因为我的IDE让我使用try / catch子句重新格式化我的代码。任何帮助将不胜感激。
提前致谢, 圣地亚哥
答案 0 :(得分:0)
只需将"everything"
声明为类中类的全局变量,因此不要在方法中声明变量"everything"
。
就这样做
public class yourclassname
{
String everything="";
private void buttonEncryptActionPerformed(java.awt.event.ActionEvent evt) {
//and do you stuff here
}
private void buttonOKEncryptActionPerformed(java.awt.event.ActionEvent evt) {
//and do you stuff here
}
}