【发布时间】:2019-11-17 04:34:06
【问题描述】:
简而言之:
我怎样才能知道,image 的背景加载在imageView.setImage(image) 导致显示空白图片之前失败,尽管image.isError==false 和image.getException==null?
背景:
在我基于 JavaFX 的简单照片查看器应用程序中,我使用 TableView() 来显示包含 jpg 文件的目录。每当一个选择表中的条目时,使用JavaFx图像类加载图片,并使用imageView显示。
我在 Image-constructor 的参数中使用 true 在后台加载照片。
加载照片后,我会将其保存在列表中(“缓存”),以便更快地“再次显示”
这里是代码sn-p:
public Object getMediaContent() {
Image image = (Image) content;
if (!isMediaContentValid()) { //if not already loaded or image in cache is invalid
try {
System.out.println("getMediaContent loading " + fileOnDisk);
content = new Image(fileOnDisk.toUri().toString(), true); //true=load in Background
} catch (Exception e) {
//will not occur with backgroundLoading: image.getException will get the exception
System.out.println("Exception while loading:");
e.printStackTrace();
}
} else {
System.out.println(fileOnDisk.toString() + "in Cache :-)...Error="+ image.isError() + " Exception=" + image.getException());
}
return content;
}
在isMediaContentValid()我测试
- 如果图像已经在缓存列表中
- 如果
image.isError()是false - 如果
image.getException() 是null
问题:
当用户非常快速地选择照片(例如,通过使用向下光标键)时,图像仍会在后台加载(用于缓存),而下一张照片的加载已经开始。 我的简单 chache 算法在内存不足时会出现问题,因为在开始加载但无法完成所有后台任务时可能有足够的内存。
但我预计这不是问题,因为在这种情况下image.isError() 会报告true 或image.getException() 将是!= null。所以我可以在重试之前释放内存。
但是isError() 报告false,getException() 报告null 并且图像在imageView 中显示为“空”:-(
问题:
我怎么知道,image 的后台加载在imageView.setImage(image) 之前失败了?
【问题讨论】:
-
图片还在加载过程中,既没有错误也没有异常。这些仅在图像完成加载或由于错误而停止加载时确定。那么,你为什么认为
isError会告诉你任何事情呢? -
你是对的。 fabians 的回答完美地解决了这个问题。谢谢你的帮助。英戈
标签: java image javafx imageview background-process