Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing same ImageView multiple times in the same scene on JavaFX

Tags:

javafx-2

I'm trying to build a Twitter-style ListView, and I couldn't reuse the same ImageView multiple times in the same list. Loading multiple copies seem to be wasteful and causes scrolling to slow down due to UI Virtualization. Are there any workarounds?

public class TwitterCell extends ListCell<Object> {

private static HashMap<String, ImageView> images = new HashMap<String, ImageView>();

@Override
protected void updateItem(Object tweet, boolean empty) {
  super.updateItem(tweet, empty);
  Tweet t = (Tweet) tweet;
  if (t != null) {
    String message = t.getMessage();
    setText(message);
    String imageUrl = t.getImageUrl();
    if (!images.containsKey(imageUrl)) {
      images.put(imageUrl, new ImageView(imageUrl));
    }
    setGraphic(images.get(imageUrl));
  }
}
like image 573
Chui Tey Avatar asked Oct 12 '25 01:10

Chui Tey


2 Answers

A scenegraph cannot contain the same Node twice in JavaFX, and there is no way of cloning nodes (as far as I know).

A workaround would perhaps be to make your map a HashMap store Image instead of ImageView, and change the last row to

setGraphic(new ImageView(images.get(imageUrl)));

This way you'll at least cache the loading of the actual Image, which should really be the heavy lifting part.

like image 84
minisu Avatar answered Oct 16 '25 07:10

minisu


Caching images is good way.

Also You can load images in background, it greatly improve performance.

public Image getImage(String path, boolean backload) {
   image = imageCache.get(path);
   if (image == null) {
      image = new Image(path, backload);
      imageCache.put(path, image);
   }
   return image;
}
like image 30
Nik Avatar answered Oct 16 '25 07:10

Nik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!