【问题标题】:How can I find out that JavaFX Image loading in background has failed?我怎样才能发现在后台加载 JavaFX 图像失败?
【发布时间】:2019-11-17 04:34:06
【问题描述】:

简而言之:

我怎样才能知道,image 的背景加载在imageView.setImage(image) 导致显示空白图片之前失败,尽管image.isError==falseimage.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() 会报告trueimage.getException() 将是!= null。所以我可以在重试之前释放内存。

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

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

【问题讨论】:

  • 图片还在加载过程中,既没有错误也没有异常。这些仅在图像完成加载或由于错误而停止加载时确定。那么,你为什么认为isError 会告诉你任何事情呢?
  • 你是对的。 fabians 的回答完美地解决了这个问题。谢谢你的帮助。英戈

标签: java image javafx imageview background-process


【解决方案1】:

我怎么知道,在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();
});

【讨论】:

  • 谢谢费边。 ...不知道为什么我之前有这个想法 ;-) 简单而伟大!英戈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 2018-05-06
相关资源
最近更新 更多