tableColumn setCellFactory

tableColumn setCellFactory

我是 JavaFX 的新手,我在 JavaFX 中构建了一个 table视图,这里是示例代码:

TableView<Person> table = new TableView<>();
table.setEditable(true);
final TableColumn<Person, String>nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));

将列表添加到 table 后,一切正常。
但是当我在 NameCol 之后添加这些代码时:

nameCol.setCellFactory(param -> new XCell());

public class XCell extends TableCell<Person, String> {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        setStyle(empty ? null : "-fx-font-weight: bold; -fx-alignment: center");
//...
    }
}

然后,nameColumn 中的数据丢失了。 但是当我评论该代码时:

//nameCol.setCellFactory(param -> new XCell());

所有的数据又回来了。 它是如此有线,我无法找出它有什么问题。

如果有人能解释发生了什么并修复它,我将不胜感激。

问题出在您 @Override TableCellupdateItem 方法,该方法处理单元格中的显示内容和显示方式。如果扩展 TableCell,则必须注意在单元格中显示图形或文本。

所以你应该这样做:

public class XCell extends TableCell<TestApp.Person, String> {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if(empty){  // check if the cell contains an item or not, if it not you want an empty cell without text.
            setText(null);
        }else {
            setText(item);
            setStyle("-fx-font-weight: bold; -fx-alignment: center"); // You can do the styling here.
            // Any further operations to this cell can be done here in else, since here you have the data displayed.
        }
        // Since as I see you don't have any graphics in the cell(like TextField, ComboBox,...) you 
        // don't have to take care about the graphic, but only the displaying of the text.
    }
}