Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change icon of a JLabel?

Tags:

java

swing

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?

like image 858
Better Not Known Avatar asked Oct 14 '09 16:10

Better Not Known


People also ask

How will you set icon for the JLabel?

To create a JLabel with an image icon we can either pass an ImageIcon as a second parameter to the JLabel constructor or use the JLabel. setIcon() method to set the icon.

Can JLabel be changed?

The method setText() can be used to update the text of JLabel in Swing. In Java, we create a frame where the label will be changed if we press the button.

Can JLabel display images?

With the JLabel class, you can display unselectable text and images. If you need to create a component that displays a string, an image, or both, you can do so by using or extending JLabel .

How do you put a JLabel on top of a JLabel?

The short answer is yes, as a JLabel is a Container , so it can accept a Component (a JLabel is a subclass of Component ) to add into the JLabel by using the add method: JLabel outsideLabel = new JLabel("Hello"); JLabel insideLabel = new JLabel("World"); outsideLabel. add(insideLabel);


2 Answers

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.

like image 83
camickr Avatar answered Sep 30 '22 02:09

camickr


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.

like image 33
Avrom Avatar answered Sep 30 '22 02:09

Avrom