tags:

views:

973

answers:

4

Hi guys,

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.

+3  A: 

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

Michael Myers
Thanks for the JPanel tip!I found this resource, hope it teaches me to build what i need:http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html
Dan
+5  A: 

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

Tom Hawtin - tackline
Mmm, forgot about those methods. (And they don't show up in the Javadoc unless you remember they exist.) +1
Michael Myers
A: 

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

Dan
Try the JPanel like I suggested. A little harder to implement, but it should give you what you want.
Michael Myers
setBorder(null), I think (or an empty, non-UI border).
Tom Hawtin - tackline
A: 

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

MyButton() {
    setBorder(null);
    setBackground(null);
    }
Software Monkey