简体   繁体   中英

Changing the Background of a button after it is clicked (i.e. after Action performed)

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM