簡體   English   中英

如何動態更改ImageView?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM