我如何才能发现在后台加载JavaFX图像失败?
简言之,问题是: 我如何才能发现,就在我如何才能发现在后台加载JavaFX图像失败?,java,image,javafx,imageview,background-process,Java,Image,Javafx,Imageview,Background Process,简言之,问题是: 我如何才能发现,就在imageView之前,image的后台加载失败。setImage(image)导致显示空图片,尽管image.isError==false和image.getException==null 背景: 在我简单的基于JavaFX的photoviewer应用程序中,我使用TableView()来显示包含jpg文件的目录。无论何时选择表中的一个条目,都会使用javafx图像类加载图片,并使用ImageView显示 我使用图像构造函数的参数中的true在后台加载照片
imageView之前,image
的后台加载失败。setImage(image)
导致显示空图片,尽管image.isError==false
和image.getException==null
背景:
在我简单的基于JavaFX的photoviewer应用程序中,我使用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
image.isError()
将报告true
或image.getException()
将是!=在这种情况下为空。这样我可以在重试之前释放内存
但是isError()
报告false
,getException()
报告null
,并且图像在imageView中显示为“空”:-(
问题是:
我怎样才能发现,就在imageView.setImage(image)
之前,image
的后台加载失败了
我怎样才能发现,就在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();
});
我怎样才能发现,就在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();
});
当图像仍在加载时,它既没有错误也没有异常。只有当图像已完成加载或由于错误而停止加载时,才会确定这些错误。那么,为什么您认为iError
会告诉您任何事情?您是对的。fabians的回答完美地解决了这一问题。感谢您的帮助。当图像正在加载时仍在加载时,它既没有错误也没有异常。只有当图像已完成加载或由于错误而停止加载时,才会确定这些。那么,为什么您认为,iError
会告诉您任何事情?您是对的。fabian的回答完美地解决了这一问题。谢谢您的帮助。Ingo谢谢您fabian…不知道为什么我早就有了这个想法;-)简单而伟大!谢谢你,费边。。。不知道我为什么早些时候有这个想法;-)简单而伟大!英戈