javafx 自定义ListView的CellFactory后 显示数据时出现数据重复问题

发布于 2021-12-03 05:27:54 字数 1659 浏览 781 评论 2

编译环境:
jdk 1.8.0_131
ide IDEA Community 2017.3
功能描述:
本人尝试编写一个这样的用户界面,BorderPane左侧为ListView,中心为一个Label和TextField外加一个名为Submit的Button。当在TextField中输入字符串,并点击Submit后,被输入的字符串及创建的时间,还有一个状态Pass将被显示在左侧的ListView中。
为了实现此显示功能,我重新设置了ListView的CellFactory。在CellFactory中返回一个内部类TitleCell继承了ListCell类,重写其updateItem方法。如下:

private class TitleCell extends ListCell<SimpleDocument> {

    @Override
    public void updateItem(SimpleDocument item, boolean empty){
        super.updateItem(item, empty);

        if(!empty && item != null){
            BorderPane cell = new BorderPane();

            Text title = new Text(item.getTitle());
            title.setFont(Font.font(14));

            Text date = new Text(item.getDate().toString());
            date.setFont(Font.font(10));

            Text source = new Text(item.getStatus());
            source.setFont(Font.font(10));

            cell.setTop(title);
            cell.setLeft(date);
            cell.setRight(source);

            setGraphic(cell);
        }
    }

问题出现:
编译通过,执行程序。向TextField输入字符串"abc"点击Submit结果正常。如图:

再次向TextField输入字符串"def",点击Submit,问题出现。

如上图,出现显示了两次def的问题。
为什么会如此,怎样解决?还请各位大神不吝赐教。
附源代码链接:代码

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一个人的旅程 2021-12-07 10:57:51

已经解决。

想挽留 2021-12-04 21:19:33
if(!empty && item != null){
            BorderPane cell = new BorderPane();

            Text title = new Text(item.getTitle());
            title.setFont(Font.font(14));

            Text date = new Text(item.getDate().toString());
            date.setFont(Font.font(10));

            Text source = new Text(item.getStatus());
            source.setFont(Font.font(10));

            cell.setTop(title);
            cell.setLeft(date);
            cell.setRight(source);

            setGraphic(cell);
        }else if(empty){
setText(null);
setGraphic(null);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文