我花了几个小时搜索,我无法弄清楚如何解决这个问题 . 也许我只是完全关闭,但我不断收到错误“无法引用在另一个方法中定义的内部类中的非最终变量userInput” . 如果有人可以帮我弄清楚为什么会发生这种情况或如何解决它,那将是值得赞赏的 .
我得到2个编译错误:不能在不同方法中定义的内部类中引用非最终变量userInput
和
不能在不同方法中定义的内部类中引用非final变量inputField
编辑:一些澄清,我想保持我的userInput变量不是最终的 .
这是我的代码,也许有人可以看到我做错了什么,我省略了与此错误无关的所有代码:
//Import libraries
...
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
...
public class TextGame {
public static void main(String[] args) throws FileNotFoundException {
...
String userInput = "Input";
...
// Create the window
JFrame gameWindow = new JFrame("Game");
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.setVisible(true);
// Centre the window
gameWindow.setLocationRelativeTo(null);
...
// Add input box to window
JTextField inputField = new JTextField();
inputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userInput = inputField.getText(); ****Here is where the error occurs***
}
});
gameWindow.add(inputField, BorderLayout.SOUTH);
// Size the window to what it contains
gameWindow.pack();
...
}
}
3 回答
您正在创建内部匿名类ActionListener的实例 . 如果此类使用父类中的变量,则所有此类变量都应标记为final . 那是因为这些变量被复制到内部类的自生成构造函数中 . 为了避免副本的不协调变化,它们应该是不变的 .
回答你的问题:
但是,更好的解决方案是从ActionEvent访问文本字段:
我认为你试图在除声明之外的类或方法之外访问你的变量“userInput”,你不能这样做,除非它以关键字“final”作为前缀,以便扩展变量的范围 . 例如 . final String userInput;