[英]How can I dynamically change the ImageView?
语言特点
Java的
应用:
我正在尝试创建一个基本的图像搜索器,在其中输入UPC并在ImageView上显示产品图像。
题
如何在不创建新实例的情况下用新图像动态更新ImageView,就像我在下面的当前实现中所做的那样 。
当前实施:
在我当前的实现中,我使事件处理程序创建一个新图像并将其设置到ImageView中。
searchButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
input = searchBar.getText();
image = new Image("url link" + input);
imageView.setImage(image);
searchBar.clear();
}
});
简短的答案是,这是不可避免的。 这种实现是完全正常的。 创建新的Image
并将其设置为ImageView
,旧的Image
会丢失引用,并且可以进行垃圾回收。
长答案是,您可以在一定程度上控制此行为。 您可以借助SoftReference
保留这些图像的缓存。
Map<String, SoftReference<Image>> imageCache = new HashMap<>();
.....
searchButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
input = searchBar.getText();
final String urlString = "url link" + input; // Or whatever the URL
final SoftReference<Image> softRef = imageCache.get(urlString);
Image image = null;
if (softRef == null || softRef.get() == null) {
image = new Image(urlString);
imageCache.put(urlString, new SoftReference<>(image));
}
else
image = softRef.get();
imageView.setImage(image);
searchBar.clear();
}
});
这将允许您的控制器存储图像的缓存,直到Java堆空间不足为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.