我必须使用ListView显示5000个节点。每个节点都包含复杂的控件,但节点中只有一些文本部分不同。如何在重新滚动时重用现有节点控件来重新创建单元格
答案 0 :(得分: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 Devs知道,例如,我们会使用StringBuilder进行字符串连接,特别是在代码经常执行的情况下。 如果您想要一些复杂的渲染,您可以使用其他节点构建该图形,并使用setGraphic()将它们设置为graphics属性。这类似于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);
}
}
};
}
});