2

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Matthew Kemnetz
  • 845
  • 1
  • 15
  • 28
  • BTW - which class has a `setIcon(String)` method? When you say it 'does not work', do you mean it 'does not compile', or ..what? – Andrew Thompson Dec 05 '11 at 06:56
  • still don't get it (and somebody got a downvote from me for the mixup in an answer :-) how do you think an _icon_ related to _background_? – kleopatra Dec 05 '11 at 10:49

2 Answers2

4

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.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

You can create your own listener that implements the MouseListener. This way, you can control when the background of the button changes (when the mouse is released, pressed, etc). Here is an example

//Add the listener to the button
      myButton.addMouseListener(new customActionListener());

//Create the listener
    class customActionListener implements MouseListener {
        public void mouseExited(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        Icon icon = new ImageIcon("icon.gif");
        myButton.setIcon(icon);

        }

        public void mouseClicked(MouseEvent e) {
        }
    }

At whatever point you want to set the background back to its default, use:

myButton.setIcon(new ImageIcon());

Johnny Rocket
  • 1,394
  • 3
  • 17
  • 25