假设我有两个属性,我想将第三个属性绑定为等于它们之间的计算。

在此示例中,我有一个val1factor属性。我希望将result属性绑定到两者的“力量”:result = Math.pow(factor, val1)

以下MCVE显示了我当前正在尝试这样做的方式,但是绑定不正确。

import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;

public class Main {

    private static DoubleProperty val1 = new SimpleDoubleProperty();
    private static DoubleProperty factor = new SimpleDoubleProperty();
    private static DoubleProperty result = new SimpleDoubleProperty();

    public static void main(String[] args) {

        // Set the value to be evaluated
        val1.set(4.0);
        factor.set(2.0);

        // Create the binding to return the result of your calculation
        result.bind(Bindings.createDoubleBinding(() ->
                Math.pow(factor.get(), val1.get())));

        System.out.println(result.get());

        // Change the value for demonstration purposes
        val1.set(6.0);
        System.out.println(result.get());
    }
}


输出:

16.0
16.0


因此,这最初似乎可以正确绑定,但是当更改resultval1时,factor不会更新。

如何正确绑定此计算?

最佳答案

除了其Bindings.createDoubleBinding之外,Callable<Double>方法还采用表示绑定依赖性的Observable变量。仅当列出的依赖项之一更改时,绑定才会更新。由于未指定任何绑定,因此绑定在创建后将永远不会更新。

要更正您的问题,请使用:

result.bind(Bindings.createDoubleBinding(
    () -> Math.pow(factor.get(), val1.get()),
    val1,
    factor));

07-24 09:39
查看更多