JavaFX中的着色表行

rak*_*afo 6 javafx tableview javafx-8

这个问题与有关.现在我想为字段值等于某个值的行着色.

    @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("");
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*s_D 16

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

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("");
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,如果instrumentId显示行时更改的值,则使用上面的代码颜色不会自动更改,除非您执行一些额外的工作.实现这一目标的最简单方法instrumentIdProperty()是使用提取器构造项目列表,该提取器返回(假设您使用的是JavaFX属性模式FaDeal).

  • 是的,但如果未显示该列,则单元工厂将无法工作.(因为表视图不会在属于不可见列的单元工厂上调用`updateItem`,原因很明显.)这就是这个问题的重点...... (2认同)