我是JavaFX新手,我用JavaFX构建了一个表视图,下面是示例代码:
TableView<Person> table = new TableView<>();
table.setEditable(true);
final TableColumn<Person, String>nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));在我将列表添加到表中之后,一切都正常。
但是,当我在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());所有的数据又回来了。它是如此的有线,以至于我无法找出有什么问题。
如果有人能解释一下发生了什么并解决它,我将不胜感激。
发布于 2017-10-25 08:53:06
问题在于,您需要@Override TableCell的updateItem方法,它处理单元格中的内容和显示方式,如果扩展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.
}
}https://stackoverflow.com/questions/46927484
复制相似问题