【问题标题】:how to bind inverse boolean, JavaFX如何绑定反布尔值,JavaFX
【发布时间】:2015-06-19 09:47:42
【问题描述】:

我的目标是绑定这两个属性,例如选择checkbox 987654322 @启用@ 987654322和反之亦然。

CheckBox checkbox = new CheckBox("click me");
Pane paneWithControls = new Pane();

checkbox.selectedProperty().bindBidirectional(paneWithControls.disableProperty());

使用此代码,但它与我想要的相反。我需要类似反向布尔绑定的东西。有没有可能,还是我必须制定一个方法来处理它?

【问题讨论】:

    标签: java binding boolean javafx-8


    【解决方案1】:

    如果只需要单向绑定,可以使用BooleanProperty中定义的not()方法:

    paneWithControls.disableProperty().bind(checkBox.selectedProperty().not());
    

    这可能是您想要的,除非您确实有其他不涉及checkBox 的更改disableProperty() 的机制。在这种情况下,您需要使用两个侦听器:

    checkBox.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> 
        paneWithControls.setDisable(! isNowSelected));
    
    paneWithControls.disableProperty().addListener((obs, wasDisabled, isNowDisabled) ->
        checkBox.setSelected(! isNowDisabled));
    

    【讨论】:

    • paneWithControls.disableProperty().bind(checkBox.selectedProperty().not()); 这给了我编译器错误:方法 bind(BooleanBinding) 未定义为 ReadOnlyBooleanProperty 类型
    • 反之:checkbox.selectedProperty().bind(paneWithControls.disableProperty().not()); 在我单击复选框时出现异常java.lang.RuntimeException: CheckBox.selected : A bound value cannot be set.
    • 我想你一定是用 disabledProperty 而不是 disableProperty
    • FXML 怎么样?如果我们有一个CheckBoxfx:id=abc,那么这样的代码:<TextField disable=${abc.selected}/> 将导致在选中复选框时禁用文本字段。未选中时我们如何获得相同的行为?
    【解决方案2】:
    checkbox.selectedProperty().bindBidirectional(paneWithControls.disableProperty().not());
    

    应该工作

    【讨论】:

      【解决方案3】:

      使用EasyBind library 可以轻松地从checkbox.selectedProperty() 创建一个新的ObservableValue,它的值反转。

      paneWithControls.disableProperty().bind(EasyBind.map(checkbox.selectedProperty(), Boolean.FALSE::equals));
      

      【讨论】:

        【解决方案4】:

        【讨论】:

        • ...disableProperty().not()
        • 但它返回 BooleanBinding 值。我不能像上面的例子那样使用它。
        猜你喜欢
        • 2018-01-17
        • 1970-01-01
        • 2018-01-29
        • 1970-01-01
        • 2020-04-15
        • 2011-01-27
        • 2021-10-02
        • 1970-01-01
        相关资源
        最近更新 更多