Accessing an "unnamed" Jbutton in an anonymous class from another anonymous class?

I created 26 JButtonin anonymous actionListener

labeled as each letter of the alphabet.

for (int i = 65; i < 91; i++){
    final char c = (char)i;
    final JButton button = new JButton("" + c);
    alphabetPanel.add(button);
    button.addActionListener(
        new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                letterGuessed( c );
                alphabetPanel.remove(button);
            }
        });
        // set the name of the button
        button.setName(c + "");
} 

      

Now I have an anonymous class keyListener

where I would like to disable the button based on which a letter was pressed on the keyboard. So if the user presses A, the button is Adisabled. Is this even possible with my current implementation?

+1


source to share


3 answers


Could you just declare an array of 26 JButton objects at the class level so that both listeners can access them? I believe that anonymous inner classes can access class variables as well as final variables.



+6


source


I don't know if you want to disable the button or if you want to remove it? In the code you are calling it is removed and in your answer you are talking about disconnecting. You can achieve this by adding a KeyListener to alphabetPanel. So you can add this just before starting the for-loop:

InputMap iMap = alphabetPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap aMap = alphabetPanel.getActionMap();

      



and instead of your ActionListener added to the JButton call, do this:

iMap.put(KeyStroke.getKeyStroke(c), "remove"+c);
aMap.put("remove"+c, new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
        // if you want to remove the button use the following two lines
        alphabetPanel.remove(button);
        alphabetPanel.revalidate();
        // if you just want to disable the button use the following line
        button.setEnabled(false);
    }
});

      

+1


source


You can also iterate over components by comparing getText () to the key pressed.

As mentioned, anonymous classes can also refer to members of the outer class as well as local finals

0


source







All Articles