MarryS
MarryS

Reputation: 175

JavaFX - Databinding - Add an addition BooleanBinding

Let's assume I have have a visibleProperty() of a Control, which is bound to a BooleanProperty somewhere in the application.

What i wanted to achieve is to add an additional binding in antoher piece of code to get sure that the visibility is e.g. always false, no matter of its existing or upcoming bindings. However it should never be possible to set the visiblity to true, if there is a binding which returns false. So I need to implement a kind of boolean logic.

The first attempt was to use OR/AND-concatinations.

tableColumn.visibleProperty().and(Bindings.createBooleanBinding(() -> false));

But as you see in the following example, this can never work.

public static void main(String[] args) {
    BooleanProperty a = new SimpleBooleanProperty(false);
    BooleanProperty b = new SimpleBooleanProperty(true);
    a.bind(b);
    System.out.println(a.get());
    a.and(Bindings.createBooleanBinding(() -> false));
    System.out.println(a.getValue());    
}

Maybe someone of you has a more creative idea.

Thx, Marry

Upvotes: 1

Views: 539

Answers (1)

DVarga
DVarga

Reputation: 21799

In this case you can simply add an additinal binding to the visibleProperty.

Example:

The visibleProperty of the first Button is bound to the selectedProperty of the ToggleButton, therefore as you press the toggle, the button is visible or unvisible.

If the third button is pressed, a new binding is added to the visibleProperty of the first Button which always remains false. From this moment the ToggleButton has no effect.

BorderPane root = new BorderPane();

Button b = new Button("Button");
ToggleButton tb = new ToggleButton("Make Button invisible");

b.visibleProperty().bind(tb.selectedProperty().not());

Button overrideBinding = new Button("Make Button invisible forever");
overrideBinding.setOnAction(e -> b.visibleProperty().bind(new SimpleBooleanProperty(false)));

root.setCenter(new VBox(b, tb, overrideBinding));

Important note: If you switch the order of the bindings (false at first then the binding with the ToggleButton) the result will be different. In this case the visibility will be changing based on the selected state of the toggle (you can think as the second one "overwrites" the first one).

Note #2: In your example when you are doing this:

a.and(Bindings.createBooleanBinding(() -> false));
System.out.println(a.getValue());    

on the first line you are creating a new BooleanBinding but you do not assign it to anywhere, therefore it has no effect on a.

You could update it to see the results as:

BooleanBinding andBinding = a.and(Bindings.createBooleanBinding(() -> false));
System.out.println(andBinding.getValue());

Note #3: If you try to create a binding like in your example

a.bind(a.and(Bindings.createBooleanBinding(() -> false)));

It will most probably result in a StackOverflowError.

Upvotes: 2

Related Questions