Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

tableview - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...