views:

346

answers:

3

Hey all,

alright I know this sounds a little far-fetched, but let me explain. I created 26 JButtons 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?

Thanks in advance,

Tomek

+6  A: 

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.

JTeagle
Or even store them in a Map keyed by character, so you could look up a JButton instance by the character.
Phill Sacre
A: 

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);
    }
});
reallyinsane
A: 

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

Johannes Schaub - litb