Tomek
Tomek

Reputation: 4829

Accessing a "nameless" Jbutton in an anonymous class from another anonymous class?

I created 26 JButton in an 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 keyListener class, where I would like to disable the button based off of which letter was pressed on the keyboard. So if the user presses A, then the A button is disabled. Is this even possible given my current implementation?

Upvotes: 1

Views: 972

Answers (3)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506905

You could also iterate through the components, comparing getText() to the key pressed.

As someone else mentioned, anonymous classes can also access members of the outer class as well as local finals

Upvotes: 0

reallyinsane
reallyinsane

Reputation: 1232

I don't know if you want to disable the button or do you want to remove it? In you code you're calling remove and in your answer you're talking about disabling. You could achieve this by adding a KeyListener to the alphabetPanel. So you could 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 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);
    }
});

Upvotes: 1

JTeagle
JTeagle

Reputation: 2196

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

Upvotes: 6

Related Questions