3

我想将 TableViewCell 中的 CheckBox 绑定到 BooleanBinding。下面的示例由一个带有列的 TableViewnameisEffectiveRequired. 列中的复选框绑定到表达式: isRequired.or(name.isEqualTo("X"))

因此,当行中的项目是必需的或名称是 X 时,该项目是“有效必需的”,那么表达式应该为真。不幸的是,CheckBox 没有反映更改。为了调试,我添加了一个文本字段,显示namePropertyrequiredProperty计算的effectiveRequiredProperty

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

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

4

1 回答 1

5

CheckBoxXXCells 在绑定所选状态 fi 时不符合他们的文档(即使没有明确设置,这里引用只是为了签名):

公共最终回调<Integer,​ObservableValue<Boolean>>getSelectedStateCallback()

返回屏幕上显示的 CheckBox 所绑定的回调。

清楚地谈论 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;
});
于 2020-03-04T11:01:41.300 回答