我可以使用 CSS 来设置单元格的样式,但是如果我想要一个不同的样式(比如使用不同的文本颜色)只为一列怎么办。
也许我错过了一些东西。
您应该使用TableColumn#setCellFactory()自定义单元格项目呈现。
例如,具有这样的Person 类的数据模型:
// init code vs..
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
firstNameCol.setCellFactory(getCustomCellFactory("green"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
lastNameCol.setCellFactory(getCustomCellFactory("red"));
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);
// scene create code vs..
和常用getCustomCellFactory()
方法:
private Callback<TableColumn<Person, String>, TableCell<Person, String>> getCustomCellFactory(final String color) {
return new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
@Override
public TableCell<Person, String> call(TableColumn<Person, String> param) {
TableCell<Person, String> cell = new TableCell<Person, String>() {
@Override
public void updateItem(final String item, boolean empty) {
if (item != null) {
setText(item);
setStyle("-fx-text-fill: " + color + ";");
}
}
};
return cell;
}
};
}