我有一个由多个可观察到的SimpleDoubleProperty组成的模型,我现在有一个程序,它根据可观察到的属性的变化来运行函数。
我现在确实有了一个calculateThings函数,它在更改时被调用:
public double calculateThings() {
return getA() + getB() + getC();
}为了触发这个函数,我给每个属性都附加了一个ChangeListener:
aProperty().addListener(observable -> calculateThings());
bProperty().addListener(observable -> calculateThings());
cProperty().addListener(observable -> calculateThings());是否有可能将一个ChangeListener添加到多个属性,以简化更改侦听?绑定API不适合这里,计算相当复杂。
像这样:
commonObservable().addListener(observable -> calculateThings());发布于 2017-07-06 22:23:27
您可以使用绑定API进行任意复杂的计算,例如使用自定义绑定:
DoubleBinding computed = new DoubleBinding() {
{
super.bind(aProperty, bProperty, cProperty);
}
@Override
public double computeValue() {
return getA() + getB() + getC() ;
}
};或者使用Bindings.createXXXBinding(...)实用程序方法:
DoubleBinding computed = Bindings.createDoubleBinding(
() -> getA() + getB() + getC(),
aProperty, bProperty, cProperty);在这两种情况下,当绑定的任何属性(示例中的aProperty、bProperty或cProperty )发生更改时,绑定都会自动更新,您可以绑定到computed或以通常的方式添加侦听器:
someDoubleProperty.bind(computed);
computed.addListener((obs, oldComputedValue, newComputedValue) -> {
/* some code */
});https://stackoverflow.com/questions/44949043
复制相似问题