JavaFX 中的着色表行 [英] Colouring table row in JavaFX

查看:36
本文介绍了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("");
                }
            }
        });

问题是我不想在我的表中显示 tc_inst.为此,我将 SceneBuilder 中的 visible 复选框设置为 false.在这种情况下,着色部分根本不起作用.如何隐藏 tc_inst 以便着色工作?

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?

推荐答案

如果要改变整行的颜色,请使用行工厂,而不是单元工厂:

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

注意,如果在显示行时instrumentId的值发生变化,那么颜色不会随着上面的代码自动变化,除非你做一些额外的工作.实现这一目标的最简单方法是使用返回 instrumentIdProperty() 的提取器构建您的项目列表(假设您在 FaDeal 中使用 JavaFX 属性模式).

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

这篇关于JavaFX 中的着色表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆