简体   繁体   中英

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

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

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

在此处输入图像描述

You may disable lines setBorder(null); setContentAreaFilled(false); 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);

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