首先
Cell
设计用于在显示不同项目时防止不必要的节点创建。因此,您不应该每次都重新创建节点
updateItem
被称为。此外,您永远不会将侦听器从
selected
这意味着可能有很多
HBox
已更新的,将不再可见的。此外,您的代码中也存在一些错误,使其无法编译。。。
不过,以下代码应该可以工作:
listView.setCellFactory(l -> new ListCell<CustomListView >() {
// create all nodes that could be displayed
private final Label itemName = new Label("item1");
private final Label price = new Label("100");
private final HBox contentContainer = new HBox();
private final Label discount = new Label("50%");
private final Label tax = new Label("5%");
private final Button button = new Button();
{
// update HBox every time the selection changes
selectedProperty().addListener((observable, oldValue, newValue) -> {
CustomListView item = getItem();
if (!isEmpty() && item != null) {
updateItemSelection(item, newValue);
}
});
}
@Override
protected void updateItem(CustomListView item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
} else {
setGraphic(contentContainer);
updateItemSelection(item, isSelected());
}
}
private void updateItemSelection(CustomListView item, boolean selected) {
// update for HBox for non-empty cells based on selection
if (selected) {
contentContainer.getChildren().setAll(itemName, price, discount, tax, button);
} else {
contentContainer.getChildren().setAll(itemName, price);
}
}
});