How to Remove an icon on a JButton?

11,272

Solution 1

Simple, Set the icon to null. It doesn't have an icon, so it removes it.

button.setIcon(null);

Solution 2

Use the following code:

  JButton button = new JButton();
  button.setIcon(null);

Solution 3

The best way to do it, is to replace the existing icon with a transparent icon of the same size. This will ensure the button does not change size, and potentially disturb the placement of other GUI elements that occur after it in the layout. E.G.

BufferedImage ourIcon = ...
BufferedImage invisibleIcon = new BufferedImage(
    ourIcon.getWidth(), ourIcon.getHeight(), BufferedImage.TYPE_INT_ARGB);

Then, simply:

// use a JToggleButton instead of a JButton - it will remain pressed
JToggleButton button = new JToggleButton(new ImageIcon(ourIcon));
button.setPressedIcon(new ImageIcon(invisibleIcon));
// start a timer to change the state back, if required..
Share:
11,272
Patrick Zawadzki
Author by

Patrick Zawadzki

Sr. Software Engineer at GE Healthcare

Updated on June 04, 2022

Comments

  • Patrick Zawadzki
    Patrick Zawadzki almost 2 years

    I'm trying to make a memory matching game, and I have icon images that I place onto a JButton when it is clicked. My question is, is there a way to remove the Icon from the JButton? I want to make so when a user clicks, the image is displayed, and if the second button the user clicks does not have the same image as the first button, then it disappears...any ideas?