gaming_enthusiast
gaming_enthusiast

Reputation: 125

Cannot refer to a non-final variable inside an inner class error when using JTextField

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


}
}

Upvotes: 4

Views: 3722

Answers (3)

Maxim Kolesnikov
Maxim Kolesnikov

Reputation: 5135

You are creating instance of inner anonymous class ActionListener. If such classes uses variables from parent class all such variables should be marked as final. That is because such variables are copied into autogenerated constructor of inner class. To avoid uncoordinated changes of copies they should be constant.

Upvotes: 0

camickr
camickr

Reputation: 324147

To answer your question:

final JTextField inputField = new JTextField();

However, a better solution is to access the text field from the ActionEvent:

JTextField textField =  (JTextField)e.getSource();
userInput = textField.getText();

Upvotes: 5

vivek.kartha
vivek.kartha

Reputation: 318

I think you are trying to access your variable "userInput" outside a class or method other than where it was declared, you cannot do this unless it's prefixed with the keyword "final" so that the scope of the variable is extended. eg. final String userInput;

Upvotes: 0

Related Questions