JavaFX TableView中的属性绑定不起作用

我按照许多链接,在表格视图中找到了一个显示复选框的解决方案。 但是我无法在表视图中更改checkbox的值。

链接我遵循: 如何将CheckBox添加到JavaFX中的TableView

型号类:

public class TUser { private SimpleStringProperty name; private SimpleStringProperty address; private SimpleBooleanProperty active; public TUser(String name, String address, boolean active) { this.name = new SimpleStringProperty(name); this.address = new SimpleStringProperty(address); this.active = new SimpleBooleanProperty(active); } public String getName() { return name.get(); } public void setName(String name) { this.name = new SimpleStringProperty(name); } public String getAddress() { return address.get(); } public void setAddress(String address) { this.address = new SimpleStringProperty(address); } public boolean getActive() { return active.get(); } public void setActive(boolean active) { this.active = new SimpleBooleanProperty(active); } } 

FXML文件:

           

控制器类:

 public class UserManagement extends AnchorPane { @FXML private TableView usertable; @FXML private TableColumn address; @FXML private TableColumn name; @FXML private TableColumn active; public UserManagement() throws IOException { initGraphics(); initTable(); } private class CheckBoxCellFactory implements Callback<TableColumn, TableCell> { @Override public TableCell call(TableColumn p) { return new CheckBoxTableCell(); } } private void initGraphics() throws IOException { FXMLLoader content = new FXMLLoader(getClass().getResource("/mypack/fxmls/UserManagement.fxml")); content.setController(this); Node contentnode = (Node) content.load(); AnchorPane.setBottomAnchor(contentnode, 0.0); AnchorPane.setLeftAnchor(contentnode, 0.0); AnchorPane.setRightAnchor(contentnode, 0.0); AnchorPane.setTopAnchor(contentnode, 0.0); getChildren().add(contentnode); active.setCellFactory(new CheckBoxCellFactory()); address.setCellValueFactory(new PropertyValueFactory("address")); name.setCellValueFactory(new PropertyValueFactory("name")); active.setCellValueFactory(new PropertyValueFactory("active")); } private void initTable(){ ObservableList data = FXCollections.observableArrayList(new TUser("ABC", "ABC Road", true)); usertable.setItems(data); } } 

输出:

的TableView

要使复选框正确绑定到模型类中的属性,需要定义属性访问器方法:

 public class TUser { // other methods and fields as before.... public BooleanProperty activeProperty() { return active ; } } 

为您的其他属性定义类似的方法可能是个好主意。

请注意,您的表格不可编辑,因此用户无法操纵复选框。 如果您希望它们可编辑,请使TableView可编辑:

  

默认情况下, TableColumn是可编辑的。