How can I create in a Swing interface a toggle image button? I have two images, imageon.jpg and imageoff.jpg,and I basically want a clickable element that toggles the images and fires an event.
Update: Is there a way to override the usual 'chrome' around the image? I would prefer a simple image to a button with an image inside.
Load the images with ImageIcon
. Create a JToggleButton
. Then apply the icons with AbstractButton.setIcon/setPressedIcon/setSelectedIcon
. Remove the border with AbstractButton.setBorderPainted(false)
.
How about JToggleButton
? You can subclass it and override paint()
to paint the correct image based on whether it is selected or not.
Another way would be to subclass JPanel
and catch mouse clicks, overriding paintComponent()
to draw the correct image. This way the only thing that gets drawn is the actual image (unlike the JToggleButton
option).
I had the same problem with JButtons. Try this:
result = new JButton( icon );
result.setBorderPainted( false );
result.setContentAreaFilled( false );
width = icon.getIconWidth();
height = icon.getIconHeight();
result.setPreferredSize( new Dimension( width, height ) );
It is necessary to set the preferred size to get rid of additional space around the button. This worked for me on Windows 7 and Mac OS X 10.6.
Your best bet is to subclass AbstractButton, and set properties like border and background (in your constructor).
MyButton() {
setBorder(null);
setBackground(null);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With