【发布时间】:2013-03-31 21:55:00
【问题描述】:
我花了几个小时搜索,但我不知道如何解决这个问题。也许我只是完全关闭,但我不断收到错误“无法在以不同方法定义的内部类中引用非最终变量 userInput”。如果有人可以帮助我弄清楚为什么会发生这种情况或如何解决它,那将不胜感激。
我得到 2 个编译错误: 不能在不同方法中定义的内部类中引用非最终变量 userInput
和
不能在不同方法中定义的内部类中引用非最终变量 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();
...
}
}
【问题讨论】:
-
userInput是main的局部变量。它必须是实例或静态(类)成员,Java 才能让您从除main的上下文之外的任何地方修改它。在这种情况下,您可以将其设置为TextGame上的字段(静态或实例,取决于您是否打算拥有该类的实例)。
标签: java swing variables compiler-errors jtextfield