Java 如何更改 JLabel 的图标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1567445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:10:09  来源:igfitidea点击:

How to change icon of a JLabel?

javaswing

提问by Better Not Known

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?

我有一个 jlabel 来显示生成的图像。但它只在第一次有效。之后,jlabel 的 imageicon 不会改变。可能是什么问题呢?

回答by camickr

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.

您可能有两个 JLabel 实例。一个是类变量,一个是已添加到 GUI 的实例变量。问题是您的代码正在更新类变量。

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

或者,如果您不更新 EDT 上的图标,您可能会遇到问题。

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.

如果您需要更多帮助,请发布您的SSCCE.

回答by Avrom

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.

另一种可能性是您有两个引用同一图像的图标对象,因此在标签上设置它似乎没有影响。

回答by Michael Shenouda

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

如果你有 jlabel 定义 JLabel label = new JLabel();

I mean the label that you used for displaying the image

我的意思是你用来显示图像的标签

inside the event function , get it out of it

在事件函数里面, 把它弄出来