Search code examples
javabindingbooleanjavafx-8

how to bind inverse boolean, JavaFX


My goal is to bind these two properties such as when checkbox is selected then paneWithControls is enabled and vice-versa.

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

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

with this code however its opposite to what I want. I need something like inverse boolean binding. Is it possible or do I have to make a method to deal with it?


Solution

  • If you want only a one-way binding, you can use the not() method defined in BooleanProperty:

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

    This is probably what you want, unless you really have other mechanisms for changing the disableProperty() that do not involve the checkBox. In that case, you need to use two listeners:

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