代码之家  ›  专栏  ›  技术社区  ›  Zephyr

如何将值绑定到计算结果?

  •  1
  • Zephyr  · 技术社区  · 6 年前

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

    在这个例子中,我有一个 val1 以及 factor 财产。我想要 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
    

    所以这看起来一开始是正确的,但是 结果 在以下情况下不更新 Val1 因素 已更改。

    如何正确绑定此计算?

    1 回复  |  直到 6 年前
        1
  •  4
  •   VeeArr    6 年前

    这个 Bindings.createDoubleBinding 方法除了 Callable<Double> ,一大群 Observable 表示绑定的依赖项。仅当所列依赖项之一被更改时,绑定才会更新。由于您没有指定任何绑定,因此绑定在创建后永远不会更新。

    若要更正问题,请使用:

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