I am trying to change the background of a JButton after it is clicked. Currently my buttons are located in a GridLayout (3x3) and look like this:
tiles.add(new JButton(new AbstractAction("") {
@Override
public void actionPerformed(ActionEvent e) {
this.setIcon("foo.png");
}
}));
This does not work. How do I manipulate the background of the image from within the actionperformed?
A JToggleButton
might be ideal for this, as shown on Swing JToolbarButton pressing
Note that you would need to add some code to ensure a button was only clickable once.
Alternately you might use a standard JButton
and call AbstractButton.setDisabledIcon(Icon)
. Disable the button when clicked, and it will flip to the alternate icon.