4

I have spent hours searching and I cannot figure out how to fix this. Maybe I'm just completely off, but I keep getting the error "Cannot refer to a non-final variable userInput inside an inner class defined in a different method". IF somebody could help me figure out why this occurs or how to fix it, that would be appreciated.

I get 2 compilation errors: Cannot refer to a non-final variable userInput inside an inner class defined in a different method

and

Cannot refer to a non-final variable inputField inside an inner class defined in a different method

EDIT: Some clarification, I want to keep my userInput variable as not final.

Here's my code, maybe somebody can see what I'm doing wrong, I've omitted all the code that has nothing to do with this error:

//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();
    ...


}
}
4

3 回答 3

5

要回答您的问题:

final JTextField inputField = new JTextField();

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

JTextField textField =  (JTextField)e.getSource();
userInput = textField.getText();
于 2013-03-31T22:00:37.063 回答
0

我认为您正试图在声明它的位置以外的类或方法之外访问变量“userInput”,除非它以关键字“final”为前缀,以便扩展变量的范围,否则您不能这样做。例如。最终字符串用户输入;

于 2013-03-31T21:58:58.083 回答
0

您正在创建内部匿名类 ActionListener 的实例。如果此类类使用来自父类的变量,则所有此类变量都应标记为 final。那是因为这些变量被复制到内部类的自动生成的构造函数中。为了避免副本的不协调更改,它们应该是恒定的。

于 2013-03-31T22:11:24.987 回答