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

查看:131
本文介绍了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()(假设您在<$ c $中使用JavaFX属性模式) c> FaDeal )。

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天全站免登陆