gpt4 book ai didi

javafx - 将 ChangeListener 附加到多个属性

转载 作者:行者123 更新时间:2023-12-02 06:41:48 25 4
gpt4 key购买 nike

我确实有一个由多个可观察的 SimpleDoubleProperty 组成的模型,我现在有一个程序,它根据可观察属性的变化运行一个函数。

我现在有一个函数calculateThings,它会在变化时被调用:

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

为了触发该函数,我将 ChangeListener 附加到每个属性:

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

是否可以将 ChangeListener 添加到多个属性以简化更改监听? Bindings API 不适合这里,计算相当复杂。

喜欢:

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

最佳答案

您可以使用 Bindings API 进行任意复杂的计算,例如使用自定义绑定(bind):

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);

无论哪种情况,当任何绑定(bind)属性(示例中的 aPropertybPropertycProperty)发生更改时,绑定(bind)都会自动更新,您可以绑定(bind)到计算或以通常的方式添加监听器:

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

关于javafx - 将 ChangeListener 附加到多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com