我想通过幂来绑定两个DoubleProperties
。那就是我想做这样的事情:
val1.bindBidirectional(2^val2);
这似乎是不可能的(请参阅文档(。为什么会这样,达到相同结果的最佳方法是什么?它是否以聪明的方式制作了两个ChangeListener
?
谢谢
Bindings
类提供了几种有用的方法来完成此操作。 其中一种方法是允许您定义自己的绑定代码的createDoubleBinding()
方法。
您在这里要做的是使用Math.pow()
方法绑定val1
来计算幂。Math.pow()
需要两个参数:功率因数和应用它的值:
val1.bind(Bindings.createDoubleBinding(() ->
Math.pow(2, val1.get()), val1));
下面是演示该概念的 MCVE:
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
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()), val1, factor));
System.out.println(result.get());
// Change the value for demonstration purposes
val1.set(6.0);
System.out.println(result.get());
}
}
创建绑定时,请务必注意,createDoubleBinding()
接受一个varargs
参数,该参数允许您指定绑定所依赖的所有Observable
对象。 在您的情况下,它只是val2
,但在上面的例子中,我也传递了一个factor
属性。
仅当一个或多个依赖属性发生更改时,才会更新绑定值。
非常感谢 VeeArr 在开发此答案时帮助解决我自己的问题!