File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes JLabel changes icon when clicked! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JLabel changes icon when clicked!" Watch "JLabel changes icon when clicked!" New topic

JLabel changes icon when clicked!

Maron Balinas

Joined: Apr 26, 2013
Posts: 3
I have 2 imageIcon for one JLabel and I just did that when I clicked it the imageIcon will change, but I just what to do that the imageIcon will change vice versa when you click it repeatedly. Is it possible that the JLabel first imageIcon alternating to the second imageIcon when you clicked?

I'm doing it for switch image that turns on and off and I coded it in class that extends JLabel.

Thanks for help in advance and sorry for my explanation and English.
Darryl Burke

Joined: May 03, 2008
Posts: 5115

Instead of reinventing the wheel, I recommend you use a JToggleButton. You can set the icon and the pressedIcon, and if you want the appearance of a label, you can set whether the border is painted and whether the contentArea is filled.

luck, db
There are no new questions, but there may be new answers.
Piet Souris
Ranch Hand

Joined: Mar 08, 2009
Posts: 971
Hi Maron,

if you DO want to use a JLabel, then simply add a MouseListener to this label. In the ML-code, every time the label is clicked, change the icon of the label. In this way, you can use as many icons as you like.

I agree. Here's the link:
subject: JLabel changes icon when clicked!
It's not a secret anymore!