Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Image as toggle button

Tags:

java

swing

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.

like image 278
Dan Burzo Avatar asked Feb 05 '09 17:02

Dan Burzo


4 Answers

Load the images with ImageIcon. Create a JToggleButton. Then apply the icons with AbstractButton.setIcon/setPressedIcon/setSelectedIcon. Remove the border with AbstractButton.setBorderPainted(false).

like image 161
Tom Hawtin - tackline Avatar answered Oct 16 '22 15:10

Tom Hawtin - tackline


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

like image 20
Michael Myers Avatar answered Oct 16 '22 14:10

Michael Myers


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.

like image 36
Andreas M. Avatar answered Oct 16 '22 13:10

Andreas M.


Your best bet is to subclass AbstractButton, and set properties like border and background (in your constructor).

MyButton() {
    setBorder(null);
    setBackground(null);
    }
like image 44
Lawrence Dol Avatar answered Oct 16 '22 15:10

Lawrence Dol