Inverse bidirectional binding for Boolean properties
Tobias Oelgarte
tobias.oelgarte at gmail.com
Thu Jun 3 20:32:50 UTC 2021
On 03.06.21 21:41, Michael Strauß wrote:
> Here's a simple thing I've come across frequently:
>
> Let's say you want to bidirectionally bind a CheckBox to a boolean
> property in a backend class (or any class that contains some kind of
> business logic).
>
> That's very easy, except if the backend property is worded in the
> "negative" (i.e. the frontend and backend values should be bound such
> that if one is true, the other is false).
>
> Since this is a very common scenario, I think it should be supported
> out-of-the-box in JavaFX by an addition to the
> `javafx.beans.binding.Bindings` class:
>
> public static void bindInverseBidirectional(
> Property<Boolean> property1,
> Property<Boolean> property2);
>
> The semantics for any two bound properties should be as follows:
> 1. If one property is `true`, the other property is `false`.
> 2. If one property is `null`, the other property is also `null`.
>
> Any thoughts?
I had a similar need to create a bidirectional binding that could
additionally convert between two types. I came up with an utility class
that provides the following method:
public static <A, B> void bindBidirectional(
Property<A> a,
Property<B> b,
Function<A, B> convertTo,
Function<B, A> convertFrom);
See https://pastebin.com/uxjp30VH
In your case one could simply write:
bindBidirectional(a, b, a -> a == null ? null : !b, b -> b == null
? null : !a);
or even simpler without null handling:
bindBidirectional(a, b, a -> !b, b -> !a);
More information about the openjfx-dev
mailing list