pfried
pfried

Reputation: 5089

Attach ChangeListener to multiple properties

I do have a model which consists of multiple observable SimpleDoubleProperty, i now have a program which runs a function depending on changes on the observable properties.

I now do have a function calculateThings which gets called on changes:

public double calculateThings() {
  return getA() + getB() + getC();
}

For triggering that function i do attach a ChangeListener to every Property:

aProperty().addListener(observable -> calculateThings());
bProperty().addListener(observable -> calculateThings());
cProperty().addListener(observable -> calculateThings());

Is there a possiblity to add a ChangeListener to multiple properties in order to simplify the change listening? The Bindings API is not suitable here, the calculations are rather complex.

Like:

commonObservable().addListener(observable -> calculateThings());

Upvotes: 6

Views: 1915

Answers (1)

James_D
James_D

Reputation: 209724

You can use the Bindings API for arbitrarily complex computations, for example using a custom binding:

DoubleBinding computed = new DoubleBinding() {
    {
        super.bind(aProperty, bProperty, cProperty);
    }

    @Override
    public double computeValue() {
        return getA() + getB() + getC() ;
    }
};

or using the Bindings.createXXXBinding(...) utility methods:

DoubleBinding computed = Bindings.createDoubleBinding(
    () -> getA() + getB() + getC(),
    aProperty, bProperty, cProperty);

In either case the binding will automatically update when any of the bound properties (aProperty, bProperty, or cProperty in the example) change, and you can either bind to computed or add listeners in the usual way:

someDoubleProperty.bind(computed);
computed.addListener((obs, oldComputedValue, newComputedValue) -> {
    /* some code */
});

Upvotes: 7

Related Questions