2016-01-13 60 views
0

我必须使用ListView显示5000个节点。每个节点都包含复杂的控件,但只有一些文本部分在节点中不同。我如何重复使用现有节点控件在滚动时重新创建我的单元格JavaFX虚拟化控件使用

+0

什么是细胞?你在使用TableView吗? – VGR

+1

如果只有文本不同,那么'ListView'的数据类型应该是'String',列表视图的'items'应该只包含5000个字符串。然后使用单元工厂来配置显示器。除了没有更多细节和代码之外,很难回答你的问题:你可能想编辑你的问题来提供这个问题。 –

回答

0

James_D的答案指向了正确的方向。通常情况下,在JavaFX中,您不必担心重复使用现有节点--JavaFX框架完全可以实现这一点,即开即用。如果你想实现一些自定义单元格呈现,你需要设置一个电池厂,这通常是这样的:

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! 
     } 
     } 

    }; 
    } 
}); 

请注意:这应该工作,但仅是说明性的 - 我们的Java离散事件知道,如,我们会使用StringBuilder进行字符串连接,特别是在代码经常执行的情况下。 如果你想要一些复杂的渲染,你可以使用额外的节点构建该图形,并使用setGraphic()将它们设置为图形属性。这与Label控件类似:

// 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); 
     } 
     } 

    }; 
    } 
}); 
+0

在第二代码中,我们创建和删除标签控件,只要我们滚动或项目的变化,有没有一种方法,我们可以缓存这个控制重用? –