在 JavaFX 中为 table 行着色
Colouring table row in JavaFX
这个问题与有关。现在我想为字段值等于某个值的行着色。
@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("");
}
}
});
问题是我不想在 table 中显示 tc_inst
。出于这个原因,我将 SceneBuilder
中的 visible
复选框设置为 false。在这种情况下,着色部分根本不起作用。如何隐藏 tc_inst
以便着色?
如果要更改整行的颜色,请使用行工厂而不是单元格工厂:
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 属性 模式)。
这个问题与
@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("");
}
}
});
问题是我不想在 table 中显示 tc_inst
。出于这个原因,我将 SceneBuilder
中的 visible
复选框设置为 false。在这种情况下,着色部分根本不起作用。如何隐藏 tc_inst
以便着色?
如果要更改整行的颜色,请使用行工厂而不是单元格工厂:
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 属性 模式)。