首页 > 解决方案 > 我怎样才能发现在后台加载 JavaFX 图像失败?

问题描述

简而言之:

我怎样才能发现,背景加载在导致显示空白图片image之前失败了?imageView.setImage(image)image.isError==falseimage.getException==null

背景:

在我基于 JavaFX 的简单照片查看器应用程序中,我使用 TableView() 来显示包含 jpg 文件的目录。Whenever one selects an entry in the table the picture is loaded using javafx Image class and is shown using an ImageView.

true我使用Image-constructor 的参数在背景中加载照片。加载照片后,我将其保存在列表(“缓存”)中,以便更快地“再次显示”

这里的代码片段:

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()我测试

问题:

当用户非常快速地选择照片(例如通过使用向下光标键)时,图像仍然在后台加载(用于缓存),而下一张照片的加载已经开始。我的简单 chache 算法在内存不足时会出现问题,因为在开始加载但无法完成所有后台任务时可能有足够的内存。

但我预计这不是问题,因为image.isError()会报告trueimage.getException()!= null在这种情况下。所以我可以在重试之前释放内存。

但是isError()报告falsegetException()报告null和图像在 imageView 中显示为“空”:-(

问题:我怎样才能知道,image之前的后台加载失败了imageView.setImage(image)

标签: javaimagejavafximageviewbackground-process

解决方案


我怎样才能知道,图像的背景加载之前失败了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();
});

推荐阅读