简体   繁体   中英

How to change icon of a JLabel?

I have a jlabel to show a generated image. But it only works the first time. After that, imageicon of the jlabel does not change. What could be the problem?

Chance are that you have two instances of the JLabel. One is a class variable and one is an instance variable which has been added to the GUI. The problem is your code is updating the class variable.

Or, maybe if you don't update the icon on the EDT you might have problems.

Edit: Just reread the question. If you are talking about a "generated image" that needs to be reloaded from a file, then you need to get rid of the cached image. Two ways to do this:

//  Using ImageIO

String imageName = "timeLabel.jpg";
imageLabel.setIcon( new ImageIcon(ImageIO.read( new File(imageName) ) ) );

//  Or you can flush the image

String imageName = "timeLabel.jpg";
ImageIcon icon = new ImageIcon(imageName);
icon.getImage().flush();
imageLabel.setIcon( icon );

If you need more help post your SSCCE .

I second the answer that there is a possibility that you have two separate label objects.

Another possibility is that you have two icon objects that reference the same image so setting it on the label appears to have no affect.

if you have the jlabel definition JLabel label = new JLabel();

I mean the label that you used for displaying the image

inside the event function , get it out of it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM