javafx - 将 CheckBoxTableCell 绑定(bind)到 BooleanBinding

标签 javafx javafx-bindings

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

因此,当行中的项目是必需的或名称是 X 时,该项目是“有效必需的”,则表达式应该为 true。 不幸的是,复选框没有反射(reflect)更改。为了调试,我添加了一个文本字段,显示 namePropertyrequiredProperty 和计算的 effectiveRequiredProperty

有趣的是,当仅返回 isRequiredProperty 而不是绑定(bind)时,复选框起作用。

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

那么就 CheckBox 而言,Property 和 ObservableValue 之间有什么区别?

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 时,不会选中该行中的复选框。它从未被检查过,就像它根本没有绑定(bind)一样。

最佳答案

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

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;
});

关于javafx - 将 CheckBoxTableCell 绑定(bind)到 BooleanBinding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60523457/

相关文章:

css - 淡入淡出过渡的 JavaFX 问题

java - JavaFX 中的 Unicode 补充平面

java - 如何在同一个窗口中依次打开2个类(class)

java - 在标签上使用 FadeTransition 会导致标签在过渡开始时显示不同

JavaFX:将 SimpleLongProperty 绑定(bind)到标签并将长值格式化为人类可读的文件大小

JavaFX 复杂字符串绑定(bind)

java - 为什么将 TextField 绑定(bind)到正在另一个线程上更新的属性最终会导致应用程序抛出错误?

java - 在 JavaFX 中绘制节点

JavaFX:双向绑定(bind)的初始值