Inverse bidirectional binding for Boolean properties

Michael Strauß michaelstrau2 at gmail.com
Thu Jun 3 23:26:29 UTC 2021


That also looks very useful, although having a converter interface
would be more similar to the existing `javafx.util.StringConverter`
class and its corresponding `BidirectionalBinding` implementations.

Such an interface could look like this:

    public interface ValueConverter<S, T> {
            T convert(S value);
            S convertBack(T value);
    }

The public `Bindings` API would then be:

    public static <T, S> void bindBidirectional(
            Property<T> property1,
            Property<S> property2,
            ValueConverter<S, T> converter)

For ease of use, some predefined converters could be added to a
convenience class `ValueConverters`.
Here's how this could be used in code:

    var p1 = new SimpleBooleanProperty();
    var p2 = new SimpleBooleanProperty();
    Bindings.bindBidirectional(p1, p2, ValueConverters.not());

    var p3 = new SimpleDoubleProperty();
    var p4 = new SimpleDoubleProperty();
    Bindings.bindBidirectional(p3, p4, ValueConverters.add(5));

Am Do., 3. Juni 2021 um 22:33 Uhr schrieb Tobias Oelgarte
<tobias.oelgarte at gmail.com>:
>
> 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