【发布时间】:2021-08-18 07:45:32
【问题描述】:
我有一个文件加载向导作为我的 Java 应用程序的一部分,允许用户将图像添加到房间。使用常见的图像编辑软件,用户将 .gif 文件保存到我的应用程序访问的指定文件夹中,以将 .gif 文件作为 JPanel 上的 JLabel 中的图标加载。这是在文件加载向导的第 3 步中使用新的 ImageIcon 完成的,它工作正常并且图标显示出来。
如果用户返回上一步(当JPanel重新加载上一步时文件从指定文件夹中删除)并使用普通图像编辑软件更新图像并使用相同名称重新保存文件。然后前进到文件加载向导的第 3 步,再次调用新的 ImageIcon,但这次它仍然显示旧的已删除图像文件的宽度和高度。 File 对象的 lastModified 值正在更改,因此我假设 File 对象正在加载更新的文件。但由于某种原因,ImageIcon 对象仍在从已删除文件中提取值。但是,如果在上一步中更改了文件名,则 ImageIcon 将在文件加载向导的第 3 步中显示正确的宽度和高度值。
图像是否缓存在新 ImageIcon 对象正在查找的位置?
这是我的文件加载向导中的代码 sn-p。这是在构建向导步骤 JPanel 的方法中。
...Other Code Here...
int height = 0;
int width = 0;
File file = new File(fileLocation);
String[] fileList = file.list();
if(fileList.length == 1){
OrginialFileName = fileList[0];
//Shouldn't this create a new instance of an ImageIcon?
//Do I need to clear a cache somewhere?
//ImageIcon object is not global and is only used locally in this conditional statement.
ImageIcon imageIcon = new ImageIcon(file + "\\" + OrginialFileName);
height = imageIcon.getIconHeight();
width = imageIcon.getIconWidth();
/*The width and height are pulling from the deleted file.
I have verified that the new file is the only file in the directory where the file loading
wizard is pulling from and the window's file properties screen shows the correct dimensions.*/
...Other Code Here...
【问题讨论】:
-
是的,
ImageIcon确实使用了缓存。你需要使用ImageIcon#getImage#flush来刷新
标签: java swing jpanel jlabel imageicon