Javafx Tableview如何为具有特定值的单元格着色 [英] Javafx Tableview How To Color Cells with Specific Value

查看:120
本文介绍了Javafx Tableview如何为具有特定值的单元格着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以只对某些特定值为TableView的单元格进行着色?

Is there a way to color only some cells with a specific value of a TableView?

Callback<TableColumn, TableCell> historyTableCellFactory
    = new Callback<TableColumn, TableCell>() {
        public TableCell call(TableColumn p) {
            TableCell newCell = new TableCell<CustomerHistoryStructure, String>() {
                private Text newText;

                @Override
                public void updateItem(String items, boolean empty) {
                    super.updateItem(items, empty);

                    if (!isEmpty()) {
                        newText = new Text(items.toString());
                        newText.setWrappingWidth(140);
                        this.setStyle("-fx-background-color:#e50000 ;");
                        setGraphic(newText);
                    }
                }

                private String getString() {
                    return getItem() == null ? "" : getItem().toString();
                }
            };
            return newCell;
        }
    };

上面的代码的问题是,当程序运行并且在TableView上滚动时,其他单元格会自己着色.

The problem with the above code is that when the program is running and I scroll on the TableView, other cells get colored on their own.

推荐答案

该代码的问题在于,您永远不会撤消添加该项目时所做的更改.即使单元格为空,也永远不会删除graphic,也永远不会检查特定值.此外,如果添加null项,则items.toString()可能会导致NPE.同样,无需重新创建Text元素.而且,您永远也不会将项目与特定值进行比较.

The problem with that code is that you never undo the changes done when the item is added. You never remove the graphic, even if the cell becomes empty and you never check for a specific value. Furthermore items.toString() could lead to a NPE, if you add null items. Also recreating the Text element is unnecessary. Also you never compare the item to a specific value.

final String specificValue = ...

new TableCell<CustomerHistoryStructure, String>() {
    private final Text newText;

    {
         newText = new Text();
         newText.setWrappingWidth(140);
    }

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

        if (empty) {
            setGraphic(null);
            setStyle("");
        } else {
            newText.setText(getString());
            setGraphic(newText);

            // adjust style depending on equality of item and specificValue
            setStyle(Objects.equals(item, specificValue) ? "-fx-background-color:#e50000 ;" : "");
        }
    }

    private String getString() {
        return getItem() == null ? "" : getItem().toString();
    }
};

这篇关于Javafx Tableview如何为具有特定值的单元格着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆