Colouring table row in JavaFX

Use a row factory, instead of a cell factory, if you want to change the color of the whole row:

tv_mm_view.setRowFactory(tv -> new TableRow<FaDeal>() {
    @Override
    public void updateItem(FaDeal item, boolean empty) {
        super.updateItem(item, empty) ;
        if (item == null) {
            setStyle("");
        } else if (item.getInstrumentId().equals("1070")) {
            setStyle("-fx-background-color: tomato;");
        } else {
            setStyle("");
        }
    }
});

Note that if the value of instrumentId changes while the row is displayed, then the color will not change automatically with the above code, unless you do some additional work. The simplest way to make that happen would be to construct your items list with an extractor which returned the instrumentIdProperty() (assuming you are using the JavaFX property pattern in FaDeal).

Leave a Comment