Java: ImageIcon - image file updating but image icon in Java frame not(Java:ImageIcon - 图像文件更新,但 Java 框架中的图像图标没有)
问题描述
I have got a ImageIcon
in a Jlabel
in a JFrame
(Java GUI).
The ImageIcon
should get updated based on pressing a Calculate button (i.e. calcButton.addActionListener(new ActionListener()
) with part of the code in the method:
icon2 = new ImageIcon("M:\Repos\rtrans\radTransPlot.png");
Plot1.setIcon(icon2);
frame.add(Plot1,gc);
frame.setVisible(true);
The initial ImageIcon
(icon1) is blank:
public class RadTransGui
{
private ImageIcon icon1 = new ImageIcon("M:\Repos\rtrans\radTransPlotEmpty.png");
private ImageIcon icon2;
private JLabel Plot1 = new JLabel(icon1);
and gets properly updated based on the first Calculate button press but not after subsequent presses of Calculate button. The contents of M:Repos trans adTransPlot.png gets updated correctly each time Calculate is pressed.
I have tried setting the ImageIcon to null and adding and removing the JLabel to the frame each time the Calculate button is pressed.
Any ideas? Thanks.
The constructor of ImageIcon() internally uses Toolkit.getDefaultToolkit().getImage
.
You have to manually use Toolkit.getDefaultToolkit().createImage
instead of Toolkit.getDefaultToolkit().getImage
. The latter uses cache whereas the former doesn't and always returns a new instance.
new ImageIcon(Toolkit.getDefaultToolkit().createImage("..filename.."))
From the javadoc of createImage
:
The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant.
Compare with the javadoc of getImage
:
The underlying toolkit attempts to resolve multiple requests with the same filename to the same returned Image. [...] If the image data contained in the specified file changes, the Image object returned from this method may still contain stale information which was loaded from the file after a prior call.
There seems to be no javadoc or spec that prescribes that ImageIcon should use cached images, so it's a perfect example of how fragile programming is if you don't know 100% what you're doing. Even if it works in one environment doesn't guarantee it always works.
这篇关于Java:ImageIcon - 图像文件更新,但 Java 框架中的图像图标没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:ImageIcon - 图像文件更新,但 Java 框架中的图像图标没有
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01