Javafx Tableview How To Color Cells with Specific Value

℡╲_俬逩灬. 提交于 2019-12-12 02:36:26

问题


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;
        }
    };

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.


回答1:


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();
    }
};


来源:https://stackoverflow.com/questions/39182782/javafx-tableview-how-to-color-cells-with-specific-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!