gpt4 book ai didi

Java:ImageIcon - 图像文件更新,但 Java 框架中的图像图标不更新

转载 作者:行者123 更新时间:2023-12-02 00:58:59 25 4
gpt4 key购买 nike

我在 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);

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

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

有什么想法吗?谢谢。

最佳答案

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

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

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% 知道自己在做什么,那么这是一个完美的例子,说明编程是多么脆弱。即使它在一种环境中有效,也不能保证它始终有效。

关于Java:ImageIcon - 图像文件更新,但 Java 框架中的图像图标不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60952313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com