问题简述:
如何才能发现,image
的后台加载在imageView.setImage(image)
之前失败了,结果显示了一个空图片,尽管image.isError==false
和image.getException==null
背景:
在我简单的基于JavaFX的照片查看器应用程序中,我使用一个TableView()来显示带有jpg文件的目录。每当选择表中的条目时,图片都使用javafx类加载,并使用ImageView显示。
我在图像构造函数的参数中使用true
加载背景中的照片。加载照片后,我将其保存在列表(“缓存”)中,以便更快地“再次显示”。
在这里,代码片段:
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()
I测试中
image.isError()
是false
image.getException(
)是null
问题是:
当用户非常迅速地选择照片(例如,通过使用光标向下键),图像仍然被加载在背景中(对于缓存),而下一张照片的加载已经开始。我的简单chache算法在内存耗尽时会出现问题,因为在启动加载时可能会有足够的内存,但不能完成所有的后台任务。
但我认为这并不是一个问题,因为在这种情况下,image.isError()
将报告true
或image.getException()
为!= null
。所以我可以在重试之前释放记忆。
但是isError()
报告false
,getException()
报告null
,图像在imageView中显示为“空”:-(
问题:我如何才能发现,image
的后台加载在imageView.setImage(image)
之前已经失败了
发布于 2019-07-07 13:04:35
如何才能发现,在
imageView.setImage(image)
之前,图像的背景加载已经失败了?
这是不可能的在后台加载图像的全部意义是异步完成的。无法保证在方法返回时已发生异常。您需要使用error
属性的侦听器来通知加载映像失败。
示例
Image image = new Image("https://stackoverflow.com/abc.jpg", true); // this image does not (currently) exist
image.errorProperty().addListener(o -> {
System.err.println("Error Loading Image " + image.getUrl());
image.getException().printStackTrace();
});
https://stackoverflow.com/questions/56921733
复制相似问题