CheckBoxTableCell为您完成了所有繁重的工作,只需要您的Person类提供一点帮助,它应该使用/公开属性(而不是只有getter/setter的普通字段)。然后使用acceptedProperty配置列,并对单元格应用自定义样式。
在代码段中:
public class Person {
private BooleanProperty accepted;
public Person(String name, boolean single) {
this.accepted = new SimpleBooleanProperty(single);
...
}
public BooleanProperty acceptedProperty() {
return accepted;
}
public boolean isAccepted() {
return acceptedProperty().get();
}
....
带单元格/值/工厂的列配置:
acceptedCol.setCellValueFactory(new PropertyValueFactory<>("accepted"));
acceptedCol.setCellFactory((TableColumn<Person, Boolean> p) -> {
CheckBoxTableCell<Person, Boolean> cell = new CheckBoxTableCell<>();
cell.getStyleClass().add("custom-cell");
cell.setAlignment(Pos.CENTER);
return cell;
});
一些自定义样式:
/**
* Just want to see an effect, doesn't matter what
*/
.custom-cell > .check-box {
-fx-background-color: blue;
}
.custom-cell > .check-box:selected {
-fx-background-color: red;
}