使用JTextField时,无法在内部类错误中引用非final变量

gam*_*ast 4 java variables swing compiler-errors jtextfield

我花了几个小时搜索,我无法弄清楚如何解决这个问题.也许我只是完全关闭,但我不断收到错误"无法引用在另一个方法中定义的内部类中的非最终变量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();
    ...


}
}
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 5

回答你的问题:

final JTextField inputField = new JTextField();
Run Code Online (Sandbox Code Playgroud)

但是,更好的解决方案是从ActionEvent访问文本字段:

JTextField textField =  (JTextField)e.getSource();
userInput = textField.getText();
Run Code Online (Sandbox Code Playgroud)