将 CheckBoxTableCell 绑定到 BooleanBinding

Bind CheckBoxTableCell to BooleanBinding

我想将 TableViewCell 中的 CheckBox 绑定到 BooleanBinding。以下示例由一个包含列 nameisEffectiveRequired 的 TableView 组成。列中的复选框绑定到表达式: isRequired.or(name.isEqualTo("X"))

所以当行中的项目是必需的或名称是 X 时,项目是 "effectivly required",则表达式应该为真。 不幸的是 CheckBox 不反映更改。为了调试,我添加了一个文本字段,显示 namePropertyrequiredProperty 和计算的 effectiveRequiredProperty

有趣的是,当仅返回 isRequired属性 而不是绑定时,复选框起作用。

public ObservableBooleanValue effectiveRequiredProperty() {
     // Bindings with this work:
     // return isRequired;
     // with this not
     return isRequired.or(name.isEqualTo(SPECIAL_STRING));
}

那么 属性 和 ObservableValue 在 CheckBox 方面有什么区别?

public class TableCellCBBinding extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }

    private void init(Stage primaryStage) {
        primaryStage.setScene(new Scene(buildContent()));
    }

    private Parent buildContent() {
        TableView<ViewModel> tableView = new TableView<>();
        tableView.setItems(sampleEntries());
        tableView.setEditable(true);
        tableView.getColumns().add(buildRequiredColumn());
        tableView.getColumns().add(buildNameColumn());

        // Add a Textfield to show the values for the first item
        // As soon as the name is set to "X", the effectiveRequiredProperty should evaluate to true and the CheckBox should reflect this but it does not
        TextField text = new TextField();
        ViewModel firstItem = tableView.getItems().get(0);
        text.textProperty()
            .bind(Bindings.format("%s | %s | %s", firstItem.nameProperty(), firstItem.isRequiredProperty(), firstItem.effectiveRequiredProperty()));

        return new HBox(text, tableView);
    }

    private TableColumn<ViewModel, String> buildNameColumn() {
        TableColumn<ViewModel, String> nameColumn = new TableColumn<>("Name");
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        nameColumn.setEditable(true);
        return nameColumn;
    }

    private TableColumn<ViewModel, Boolean> buildRequiredColumn() {
        TableColumn<ViewModel, Boolean> requiredColumn = new TableColumn<>("isEffectiveRequired");
        requiredColumn.setMinWidth(50);
        // This is should bind my BindingExpression from to ViewModel to the CheckBox
        requiredColumn.setCellValueFactory( p -> p.getValue().effectiveRequiredProperty());
        requiredColumn.setCellFactory( CheckBoxTableCell.forTableColumn(requiredColumn));
        return requiredColumn;
    }

    private ObservableList<ViewModel> sampleEntries() {
        return FXCollections.observableArrayList(
                new ViewModel(false, "A"),
                new ViewModel(true,  "B"),
                new ViewModel(false, "C"),
                new ViewModel(true,  "D"),
                new ViewModel(false, "E"));
    }

    public static class ViewModel {
        public static final String SPECIAL_STRING = "X";

        private final StringProperty name;
        private final BooleanProperty isRequired;

        public ViewModel(boolean isRequired, String name) {
            this.name = new SimpleStringProperty(this, "name", name);
            this.isRequired = new SimpleBooleanProperty(this, "isRequired", isRequired);
            this.name.addListener((observable, oldValue, newValue) -> System.out.println(newValue));
        }

        public StringProperty nameProperty() {return name;}
        public final String getName(){return name.get();}
        public final void setName(String value){
            name.set(value);}

        public boolean isRequired() {
            return isRequired.get();
        }
        public BooleanProperty isRequiredProperty() {
            return isRequired;
        }
        public void setRequired(final boolean required) {
            this.isRequired.set(required);
        }

        public ObservableBooleanValue effectiveRequiredProperty() {
            // Bindings with this work:
            // return isRequired;
            // with this not
            return isRequired.or(name.isEqualTo(SPECIAL_STRING));
        }
    }
}

在名称中输入 X 时,应选中行中的复选框。

在名称中键入 X 时,未选中行中的复选框。它从来没有被检查过,就像它根本没有被绑定一样。

CheckBoxXXCells 在绑定其选定状态时不符合其文档,f.i。 (这里引用只是为了签名,即使没有明确设置):

public final Callback <Integer,​ObservableValue<Boolean>> getSelectedStateCallback()

Returns the Callback that is bound to by the CheckBox shown on screen.

清楚地谈论了一个 ObservableValue,所以我们期望它至少 显示 选择状态。

实际上,如果它不是 属性,则该实现完全不执行任何操作,来自其 updateItem 的相关部分:

StringConverter<T> c = getConverter();

if (showLabel) {
    setText(c.toString(item));
}
setGraphic(checkBox);

if (booleanProperty instanceof BooleanProperty) {
    checkBox.selectedProperty().unbindBidirectional((BooleanProperty)booleanProperty);
}
ObservableValue<?> obsValue = getSelectedProperty();
if (obsValue instanceof BooleanProperty) {
    booleanProperty = (ObservableValue<Boolean>) obsValue;
    checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty);
}

checkBox.disableProperty().bind(Bindings.not(
        getTableView().editableProperty().and(
        getTableColumn().editableProperty()).and(
        editableProperty())
    ));

要解决此问题,请使用自定义单元格来更新其 updateItem 中的选定状态。加上我们需要禁用检查的触发以真正保持视觉效果与支持状态同步的怪癖:

requiredColumn.setCellFactory(cc -> {
    TableCell<ViewModel, Boolean> cell = new TableCell<>() {
        CheckBox check = new CheckBox() {

            @Override
            public void fire() {
                // do nothing - visualizing read-only property
                // could do better, like actually changing the table's
                // selection
            }

        };
        {
            getStyleClass().add("check-box-table-cell");
            check.setOnAction(e -> {
                e.consume();
            });
        }

        @Override
        protected void updateItem(Boolean item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || item == null) {
                setText(null);
                setGraphic(null);
            } else {
                check.setSelected(item);
                setGraphic(check);
            }
        }

    };
    return cell;
});