首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tableColumn setCellFactory

tableColumn setCellFactory
EN

Stack Overflow用户
提问于 2017-10-25 08:24:48
回答 1查看 2.8K关注 0票数 0

我是JavaFX新手,我用JavaFX构建了一个表视图,下面是示例代码:

代码语言:javascript
复制
TableView<Person> table = new TableView<>();
table.setEditable(true);
final TableColumn<Person, String>nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));

在我将列表添加到表中之后,一切都正常。

但是,当我在NameCol之后添加这些代码时:

代码语言:javascript
复制
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的数据丢失了。但当我评论这段代码时:

代码语言:javascript
复制
//nameCol.setCellFactory(param -> new XCell());

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-25 08:53:06

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

所以你应该这样做:

代码语言:javascript
复制
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.
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46927484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档