22

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?

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166

4 Answers4

36

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));
James_D
  • 201,275
  • 16
  • 291
  • 322
  • `paneWithControls.disableProperty().bind(checkBox.selectedProperty().not());` this gives me compiller error: _The method bind(BooleanBinding) is undefined for the type ReadOnlyBooleanProperty_ – Tomasz Mularczyk Apr 13 '15 at 23:20
  • the other way around: `checkbox.selectedProperty().bind(paneWithControls.disableProperty().not());` gives an exception when I click checkbox `java.lang.RuntimeException: CheckBox.selected : A bound value cannot be set.` – Tomasz Mularczyk Apr 13 '15 at 23:23
  • 2
    I think you must have used disabledProperty instead of disableProperty – James_D Apr 13 '15 at 23:35
  • how about from FXML? if we had a `CheckBox` with `fx:id=abc` then code like this: `` will cause the text field to be disabled when the checkbox is checked. How do we get the same behavior when its unchecked? – Groostav Nov 15 '15 at 00:44
1
checkbox.selectedProperty().bindBidirectional(paneWithControls.disableProperty().not());

should work

Ingo
  • 605
  • 6
  • 10
1

Using the EasyBind library one can easily create a new ObservableValue that from checkbox.selectedProperty() that has the invert of its values.

paneWithControls.disableProperty().bind(EasyBind.map(checkbox.selectedProperty(), Boolean.FALSE::equals));
Mustafa
  • 5,624
  • 3
  • 24
  • 40
0

Something like that? See link below http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/BooleanExpression.html#not--

borovsky
  • 873
  • 1
  • 9
  • 15