Change labels icon - not appearing
Hi,
I have a JLabel with an icon that is clock. After an event occurs, I want to change the icon of the label to a calendar. (logically, doesnt make sense..why a clock/calendar...its an example).
Anyway, when the event occurs, I do this:
label.setIcon("mycalendar.gif");
label.repaint();// i also tried label.revalidate();
when the event occurs, the label goes blank ...when i put mouse on it, it shows the clock again. i never see the calendar.
notes: the calendar icon exists, the path to it is correct....so all that is correct, just getting it to show is the problem.
Thanks.
i tried using the icon, it is a valid image. Both images are valid, and appear if I just set the icon to it the 1st time. Example, initially the clock appears or if i use calendar, initially the calendar appears.
The problem is that if I start with clock, then want to change it to calendar later, the calendar does not appear, the label just looks blank, until I mouse over the label...then the clock appears again.
:: kslm23 ::
No I have not tried the the invokeLater clause, how can I use that? Can you give me sample code?
Thanks.
try this:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* @author peter.de.bruycker
*/
public class ChangeIcon extends JFrame
{
private ImageIcon icon1;
private ImageIcon icon2;
private JLabel label;
private boolean first = true;
public ChangeIcon()
{
super("ChangeIcon");
this.icon1 = new ImageIcon("d:/eclipse/workspace/peter.de.bruycker/org.sourceforge.dbmonster/icons/icon-schema.png");
this.icon2 = new ImageIcon("d:/eclipse/workspace/peter.de.bruycker/org.sourceforge.dbmonster/icons/icon-dbmonster.png");
this.label = new JLabel(icon1);
JButton button = new JButton("Change icon");
button.addActionListener(new ActionListener()
{
/**
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
toggleIcon();
}
});
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(this.label);
this.getContentPane().add(button);
}
public static void main(String[] args)
{
ChangeIcon frame = new ChangeIcon();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
private void toggleIcon()
{
if (this.first)
{
this.label.setIcon(this.icon2);
}
else
{
this.label.setIcon(this.icon1);
}
this.first = !this.first;
}
}
essentially, I am doing that. I am not using an actionlistener, but I have the same setup. If something occurs, then change icon....just like your code. Your code does, it action happens, change icon. Same idea..just different way of doing it.thanks anyway.