简体   繁体   English

如何动态更改ImageView?

[英]How can I dynamically change the ImageView?

Langauge 语言特点

Java Java的

Application: 应用:

I'm trying to create a basic image searcher where I enter a UPC and show a product image on the ImageView. 我正在尝试创建一个基本的图像搜索器,在其中输入UPC并在ImageView上显示产品图像。

Question

How can dynamically update the ImageView with a new image without creating new instances as I'm doing in my current implementation below . 如何在不创建新实例的情况下用新图像动态更新ImageView,就像我在下面的当前实现中所做的那样

Current Implementation: 当前实施:

In my current implementation I have the event handler create a new image and have it set into the 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();
        }
    });

The short answer is, it is unavoidable. 简短的答案是,这是不可避免的。 This implementation is perfectly normal. 这种实现是完全正常的。 When you create a new Image , and set it to the ImageView , the old Image loses the reference and is eligible for garbage collection. 创建新的Image并将其设置为ImageView ,旧的Image会丢失引用,并且可以进行垃圾回收。

The long answer is, you can control this behavior to certain extent. 长答案是,您可以在一定程度上控制此行为。 You can keep a cache of these images with the help of SoftReference . 您可以借助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();
    }
});

This will allows your controller to store a cache of images until the Java Heap runs out of space. 这将允许您的控制器存储图像的缓存,直到Java堆空间不足为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM