我正在用javafx编写一个座位表程序。我有一个表格,里面有一个学生的名单,上面有他们的名字,成绩,以及他们是否在场(使用复选框)。我有一个删除按钮,允许我从列表中删除学生。这很好,但是,每当我删除student对象时,复选框就不会与它一起使用。我不知道我需要补充什么才能让它发挥作用。这是一段删除代码。下面还有两张图片显示了我的问题。这是我的第一篇文章,如果我漏了什么,请告诉我。请帮忙!谢谢!
ObservableList<Student> items, sel;
items = currentTable.getItems();
sel = currentTable.getSelectionModel().getSelectedItems();
Student s = new Student("", "", 0, "");
for (Student p : sel) {
items.remove(p);
s = p;
}
删除前
删除后
最佳答案
这与delete
或remove
方法无关。这与你在TableColumn.setCellFactory()
中所做的有关。
要获得所显示的复选框,您应该(通常)使用以下两种方法之一:
设置单元格工厂时重写TableCell中的updateitem()empty
中有一个updateItem()
参数,指示行是否为空。您需要使用它来确定何时不显示复选框。
column.setCellFactory(col -> {
return new TableCell<Foo, Boolean>() {
final CheckBox checkBox = new CheckBox();
@Override
public void updateItem(final Boolean selected, final boolean empty) {
super.updateItem(selected, empty);
if (!this.isEmpty()) {
setGraphic(checkBox);
setText("");
}
else {
setGraphic(null); // Remove checkbox if row is empty
setText("");
}
}
}
}
使用checkboxTableCell
javafx api有一个方便的类
CheckBoxTableCell
可以帮您完成所有这些工作。大多数人觉得这个类很难使用,因为要确保正确使用它,需要两件事:列所属的
TableView
必须是可编辑的。TableColumn
本身必须是可编辑的。例子:
tableView.setEditable(true);
tableColumnSelected.setCellFactory(CheckBoxTableCell.forTableColumn(tableColumnSelected));
tableColumnSelected.setEditable(true);
至于是否要用delete按钮删除哪个条目,只需要从
TableView
中删除正确的条目。