Javafx Tableview How To Color Cells with Specific

2019-09-16 00:59发布

问题:

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