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?
source to share
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);
}
});
source to share