How do I set an Icon to a JButton without losing the animation when it's pressed?

Viewed 142

I have created a custom button icon using an online tool, and then I have downloaded the .png file. I have already set the icon in the JButton (Swing Application), but, when the button is pressed, it doesn't show the regular animation when a button is clicked. Is it possible to set an Icon without losing this effect? Thanks (here's the code)

public final JButton SEARCH = new JButton();
SEARCH.setBorder(null);
SEARCH.setContentAreaFilled(false);

ImageIcon searchb = new ImageIcon(getClass().getClassLoader().getResource("search.png"));
SEARCH.setIcon(searchb);
2 Answers

You have to use different icons (images) based on your requirement. that means you have to use another image which resemblance pressed button using your original image

see below

JButton b = new JButton();
b.setPressedIcon(); // shows when button is pressed 
b.setSelectedIcon(); // shows when button is selected(applicable for toggle buttons) 
b.setDisabledIcon(); // shows when button is disabled 
b.setRolloverIcon(); // shows when mouse pointer hovering on the button

enter image description here

You may disable lines setBorder(null); setContentAreaFilled(false); in order to enjoy the default animation. The animation stays, and the image is over it.

public final JButton SEARCH = new JButton();
//SEARCH.setBorder(null);
//SEARCH.setContentAreaFilled(false);

ImageIcon searchb = new ImageIcon(getClass().getClassLoader().getResource("search.png"));
SEARCH.setIcon(searchb);
Related