Search code examples
javaswingactionlistenerjtextfield

Action Listener for a JTextField fails after first "use"


I'm trying to create a small program, where you have to guess words while you are shown a matching anagram. My code is like:

        JFrame frame = generateJFrame(BACKGROUND, FOREGROUND);
        JLabel display = generateDisplay(BACKGROUND, FOREGROUND);

        Pair now = woerter.shuffle();
        display.setText(now.getAnagram());

        JTextField input = generateInputBox(BACKGROUND, FOREGROUND);
        ActionListener action = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                nextWord(now, woerter, display, input);
            }
        };

        input.addActionListener(action);
[...] 
        private static void nextWord(Pair now, Woerter woerter, JLabel display, JTextField input) {
            if (now.getRealWord().equalsIgnoreCase(input.getText())) {
            now = woerter.shuffle();
            display.setText(now.getAnagram());
            input.setText("");
            }
        }

Now when I execute it, it works the first time (when you type in the correct word and press enter a new anagram is displayed and the inputfield clears), but afterwards it breaks and enter doesn't do anything anymore. What am I doing wrong? Any help would be appreciated.


Solution

  • Pair now = woerter.shuffle();
    

    You are defining "now" as a local variable.

    now = woerter.shuffle();
    

    But you also reference it in your nextWord(…) method, which indicates you have also defined it as a static variable.

    Don't define the variable twice. Get rid of the local variable:

    //Pair now = woerter.shuffle();
    now = woerter.shuffle();
    

    Also, defining methods and variables as static indicates a poor design. Your nextWor() method should not be static and therefore the "now" variable will not need to be static.

    Read the section from the Swing tutorial on How to Use Text Fields. The TextDemo code will show you how to better structure your code so that the ActionListener of the text field can access the text field and the rest of the data in your class.

    So download the working demo code and modify it to meet your requirements.