java imageicon png,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\rtrans\radTransPlot.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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值