且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 21:37:10

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

The constructor of ImageIcon() internally uses Toolkit.getDefaultToolkit().getImage.

您必须手动使用Toolkit.getDefaultToolkit().createImage而不是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.."))

来自createImage的javadoc:

From the javadoc of createImage:

返回的Image是一个新对象,不会与该方法或其getImage变体的任何其他调用方共享.

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进行比较:

Compare with the javadoc of getImage:

基础工具包尝试将具有相同文件名的多个请求解析为相同的返回图片. [...]如果指定文件中包含的图像数据发生更改,则从该方法返回的 Image对象可能仍包含过时信息,该信息是在先前调用后从文件中加载的.

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%正在做什么,那么这是一个非常脆弱的编程的完美示例.即使它在一种环境中工作也不能保证它总是能工作.

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.