如何在 TableView 列中设置 JavaFX CheckBox 值?

How to set JavaFX CheckBox value in a TableView Column?

我正在尝试从 'Information' class 获取 'Active' 值并将其设置为 TableView Column 作为复选框,以便用户可以编辑。我的控制器中有以下内容:

activeColumn.setCellValueFactory(new PropertyValueFactory<Information, Boolean>("Active"));
            final Callback<TableColumn<Information, Boolean>, TableCell<Information, Boolean>> cellFactory = CheckBoxTableCell.forTableColumn(activeColumn);
            activeColumn.setCellFactory(new Callback<TableColumn<Information, Boolean>, TableCell<Information, Boolean>>() {
                @Override
                public TableCell<Information, Boolean> call(TableColumn<Information, Boolean> column) {
                    TableCell<Information, Boolean> cell = cellFactory.call(column);
                    cell.setAlignment(Pos.CENTER);
                    return cell ;
                }
            });
            activeColumn.setCellFactory(cellFactory);
            activeColumn.setEditable(true);

这是我的 'Information' class,其中我获得的活动值为 true/false

public Information(Hashtable information) {
    :::

    String strActive = cvtStr(information.get("Active"));
            if (strActive.equals("1"))
                this.active = true;
            else if (strActive.equals("0"))
                this.active = false;
}
 public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

当我 运行 它时,我没有选中 'Active' 为真的复选框。这是屏幕截图:

有人能告诉我我哪里做错了吗?或者还有其他方法可以完成这项工作吗?

如有任何帮助,我们将不胜感激

在模型中使用 JavaFX 属性 class:

public class Information {

    private final BooleanProperty active = new SimpleBooleanProperty();

    public Information(Hashtable information) {

        // ...

        String strActive = cvtStr(information.get("Active"));
        if (strActive.equals("1"))
            setActive(true);
        else if (strActive.equals("0"))
            setActive(false);
    }

    public BooleanProperty activeProperty() {
        return active ;
    }

    public final boolean isActive() {
        return activeProperty().get();
    }

    public final void setActive(boolean active) {
        activeProperty().set(active);
    }

    // ...

}

请注意,您的单元格值工厂(您莫名其妙地设置了两次)有错误:应该是

activeColumn.setCellValueFactory(new PropertyValueFactory<Information, Boolean>("active"));

更好的是

activeColumn.setCellValueFactory(cellData -> cellData.getValue().activeProperty());

我发现将数据对象的 属性 设置为 CheckBox 类型而不是布尔类型要简单得多。然后在表视图中使用 属性 会更容易和更直接。