我使用下面的custome單元工廠在tableCell
中獲得checkboxes
。您也可以使用相同的方法,並在此處設置onClick
偵聽器。下面是代碼:
final class BooleanCell extends TableCell<MyObject, Boolean> {
private CheckBox checkBox;
public BooleanCell() {
checkBox = new CheckBox();
checkBox.setOnAction((evt) -> {
getTableView().getItems().get(getIndex()).setCheck(new SimpleBooleanProperty(checkBox.isSelected()));
}
});
this.setGraphic(checkBox);
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setEditable(true);
}
@Override
public void startEdit() {
super.startEdit();
if (isEmpty()) {
return;
}
checkBox.requestFocus();
}
@Override
public void cancelEdit() {
super.cancelEdit();
// checkBox.setDisable(true);
}
@Override
public void commitEdit(Boolean value) {
super.commitEdit(value);
// checkBox.setDisable(true);
}
@Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
if (item != null) {
checkBox.setAlignment(Pos.CENTER);
checkBox.setSelected(item);
}
setAlignment(Pos.CENTER);
setGraphic(checkBox);
}
}
}
上面cell factory
可以如下所述被施加到tableColumn
。
Callback<TableColumn<MyObject, Boolean>, TableCell<MyObject, Boolean>> booleanCellFactory = new Callback<TableColumn<MyObject, Boolean>, TableCell<MyObject, Boolean>>() {
@Override
public TableCell<MyObject, Boolean> call(TableColumn<MyObject, Boolean> p) {
return new BooleanCell();
}
};
tbColCheck.setCellFactory(booleanCellFactory);