简体   繁体   中英

JavaFX virtualised controls use

I have to display 5000 nodes using ListView. Every node contains complex controls but only some text part is different in nodes. How can i reuse existing nodes controls to recreate my cells while scrolling

The answer of James_D points into the right direction. Normally, in JavaFX you shouldn't worry about reusing existing nodes - the JavaFX framework does exactly this, out-of-the-box. If you want to implement some custom cell rendering, you need to set a cell factory, and that usually looks like this:

 listView.setCellFactory(new Callback() {
  @Override
  public Object call(Object param) {
    return new ListCell<String>() {

      // you may declare fields for some more nodes here
      // and initialize them in an anonymous constructor

      @Override
      protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty); // Default behaviour: zebra pattern etc.

        if (empty || item == null) { // Default technique: take care of empty rows!!!
          this.setText(null);

        } else {
          this.setText("this is the content: " + item);
          // ... do your custom rendering! 
        }
      }

    };
  }
});

Please note: this should work, but is merely illustrative - we Java Devs know that eg, we would use a StringBuilder for String concatenation, especially in such cases where the code will execute very often. If you want some complex rendering, you may build that graphic with additional nodes and set them as graphics property with setGraphic(). This works similar to the Label control:

// another illustrative cell renderer: 
listView.setCellFactory(new Callback() {
  @Override
  public Object call(Object param) {
    return new ListCell<Integer>() {

      Label l = new Label("X");

      @Override
      protected void updateItem(Integer item, boolean empty) {
        super.updateItem(item, empty); 

        if (empty || item == null) {
          this.setGraphic(null);

        } else {
          this.setGraphic(l);
          l.setBackground(
                  new Background(
                          new BackgroundFill(
                                  Color.rgb(3 * item, 2 * item, item),
                                  CornerRadii.EMPTY,
                                  Insets.EMPTY)));
          l.setPrefHeight(item);
          l.setMinHeight(item);
        }
      }

    };
  }
}); 

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.

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