Cannot refer to a non-final variable inside an inner class error when using JTextField
compiler-errors, java, jtextfield, swing, variables
Solution
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();
Problem
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(); ... } } ```