如何在 JavaFX 中将 CheckBox 添加到 TableView [英] How to add CheckBox's to a TableView in JavaFX
本文介绍了如何在 JavaFX 中将 CheckBox 添加到 TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的 Java 桌面应用程序中,我有一个 TableView,我希望在其中有一列带有复选框.
In my Java Desktop Application I have a TableView in which I want to have a column with CheckBoxes.
我确实找到了这样做的地方 http://www.jonathangiles.net/javafx/2.0/CellFactories/ 但由于无法下载,而且我不知道 Jonathan Giles 多久会回复我的电子邮件,我想我会问...
I did find where this has been done http://www.jonathangiles.net/javafx/2.0/CellFactories/ but as the download is not available and because I don't know how soon Jonathan Giles will answer my email I thought I'd ask...
如何在 TableView 的单元格中放置 CheckBox?
How do I put a CheckBox in a cell of my TableView?
推荐答案
需要在TableColumn上设置一个CellFactory.
You need to set a CellFactory on the TableColumn.
例如:
Callback<TableColumn<TableData, Boolean>, TableCell<TableData, Boolean>> booleanCellFactory =
new Callback<TableColumn<TableData, Boolean>, TableCell<TableData, Boolean>>() {
@Override
public TableCell<TableData, Boolean> call(TableColumn<TableData, Boolean> p) {
return new BooleanCell();
}
};
active.setCellValueFactory(new PropertyValueFactory<TableData,Boolean>("active"));
active.setCellFactory(booleanCellFactory);
class BooleanCell extends TableCell<TableData, Boolean> {
private CheckBox checkBox;
public BooleanCell() {
checkBox = new CheckBox();
checkBox.setDisable(true);
checkBox.selectedProperty().addListener(new ChangeListener<Boolean> () {
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(isEditing())
commitEdit(newValue == null ? false : newValue);
}
});
this.setGraphic(checkBox);
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setEditable(true);
}
@Override
public void startEdit() {
super.startEdit();
if (isEmpty()) {
return;
}
checkBox.setDisable(false);
checkBox.requestFocus();
}
@Override
public void cancelEdit() {
super.cancelEdit();
checkBox.setDisable(true);
}
public void commitEdit(Boolean value) {
super.commitEdit(value);
checkBox.setDisable(true);
}
@Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (!isEmpty()) {
checkBox.setSelected(item);
}
}
}
这篇关于如何在 JavaFX 中将 CheckBox 添加到 TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文