Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colouring table row in JavaFX

This question is related to this. Now I want to colour the row where field value equals to some value.

    @FXML
    private TableView<FaDeal> tv_mm_view;
    @FXML
    private TableColumn<FaDeal, String> tc_inst;
    tc_inst.setCellValueFactory(cellData -> new SimpleStringProperty(""+cellData.getValue().getInstrumentId()));

    tc_inst.setCellFactory(column -> new TableCell<FaDeal, String>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);

                } else {

                    setText(item);
                    // Style row where balance < 0 with a different color.

                    TableRow currentRow = getTableRow();
                    if (item.equals("1070")) {
                        currentRow.setStyle("-fx-background-color: tomato;");

                    } else currentRow.setStyle("");
                }
            }
        });

The problem is I don't want to show tc_inst in my table. For this reason I set visible checkbox in SceneBuilder to false. In this case colouring part doesn't work at all. How can hide tc_inst so that colouring works?

like image 753
rakamakafo Avatar asked Aug 20 '15 13:08

rakamakafo


Video Answer


1 Answers

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).

like image 62
James_D Avatar answered Sep 21 '22 12:09

James_D