Langauge
Java
Application:
I'm trying to create a basic image searcher where I enter a UPC and show a product image on the 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 .
Current Implementation:
In my current implementation I have the event handler create a new image and have it set into the 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.
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.