java - 我怎样才能发现在后台加载 JavaFX 图像失败?
问题描述
简而言之:
我怎样才能发现,背景加载在导致显示空白图片image
之前失败了?imageView.setImage(image)
image.isError==false
image.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()
我测试
- 如果图像已经在缓存列表中
- 如果
image.isError()
是false
- 如果
image.getException(
) 是null
问题:
当用户非常快速地选择照片(例如通过使用向下光标键)时,图像仍然在后台加载(用于缓存),而下一张照片的加载已经开始。我的简单 chache 算法在内存不足时会出现问题,因为在开始加载但无法完成所有后台任务时可能有足够的内存。
但我预计这不是问题,因为image.isError()
会报告true
或image.getException()
会!= null
在这种情况下。所以我可以在重试之前释放内存。
但是isError()
报告false
、getException()
报告null
和图像在 imageView 中显示为“空”:-(
问题:我怎样才能知道,image
之前的后台加载失败了imageView.setImage(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();
});
推荐阅读
- c# - ASP.NET-Core MVC - 当用户点击 url 时如何发送 jwt 令牌?
- python - 使用 Python 在 Web-Scraping 上遇到关键错误
- c# - 使用 Visual Studio 登录时出现未处理的激活错误
- c++ - 适用于 Windows 和 Linux 的 CGAL 链接错误 QT Creator 项目
- php - 单击更新链接后表格未更新
- python - mysql-connector 不会导入到 pycharm 中的脚本中
- javascript - 更改背景图像
在 CSS 中,取决于季节(春、夏、秋、冬) - svn - Plink SVN 用户名问题
- wkhtmltopdf - 页眉页脚随机消失/错误
- javascript - 页面加载后如何自动运行功能?