Ghost items in javafx ListView with custom ListCell

前端 未结 1 408
既然无缘
既然无缘 2020-12-20 09:34

I try to view a custom object in a ListView using a custom ListCell. As an example to demonstrate the problem I chose java.util.File. Also for demonstration pur

相关标签:
1条回答
  • 2020-12-20 10:15

    You never set the disable property back to false. You need to do this for empty cells. The following could happen to a Cell:

    1. a item is added to the Cell and the cell is disabled
    2. the item is removed from the Cell, the Cell becomes empty, but it remains disabled.

    In general when a Cell becomes empty, any changes done to the Cell when an item was added should be undone.

    Furthermore you should avoid recreating the TextFields every time a new item is assigned to a Cell.

    listView.setCellFactory(column -> {
        return new ListCell<File>() {
    
            private final TextField textField = new TextField();
    
            protected void updateItem(File item, boolean empty) {
                super.updateItem(item, empty);
    
                if (item == null || empty) {
                    setDisable(false);
                    setGraphic(null);
                } else {
                    setDisable(true);
                    textField.setText(item.getName());
                    setGraphic(textField);
                }
            }
        };
    });
    
    0 讨论(0)
提交回复
热议问题