Java: ImageIcon - 图像文件正在更新,但 Java 帧中的图像图标未更新

Java: ImageIcon - image file updating but image icon in Java frame not

我在 JFrame(Java GUI)的 Jlabel 中得到了 ImageIcon

ImageIcon 应该根据按下 Calculate 按钮(即 calcButton.addActionListener(new ActionListener() )和方法中的部分代码来更新:

icon2 = new ImageIcon("M:\Repos\rtrans\radTransPlot.png");
Plot1.setIcon(icon2);
frame.add(Plot1,gc);
frame.setVisible(true);

初始ImageIcon(icon1)为空:

public class RadTransGui 
{
private ImageIcon icon1 = new ImageIcon("M:\Repos\rtrans\radTransPlotEmpty.png");
private ImageIcon icon2;
private JLabel Plot1 = new JLabel(icon1);

并根据第一次 Calculate 按钮的按下正确更新,但在随后按下 Calculate 按钮之后不会。 M:\Repos\rtrans\radTransPlot.png 的内容在每次按下 Calculate 时都会正确更新。

每次按下 计算 按钮时,我已尝试将 ImageIcon 设置为 null 并在框架中添加和删除 JLabel。

有什么想法吗?谢谢。

ImageIcon() 的构造函数内部使用了Toolkit.getDefaultToolkit().getImage.

您必须手动使用 Toolkit.getDefaultToolkit().createImage 而不是 Toolkit.getDefaultToolkit().getImage。后者使用缓存而前者不使用并且总是 returns 一个新实例。

new ImageIcon(Toolkit.getDefaultToolkit().createImage("..filename.."))

来自 createImage 的 javadoc:

The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant.

getImage的javadoc比较:

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.

似乎没有 javadoc 或规范规定 ImageIcon 应该使用缓存的图像,所以这是一个完美的例子,说明如果您 100% 不知道自己在做什么,编程是多么脆弱。即使它在一个环境中工作也不能保证它总是有效。