【发布时间】:2018-07-05 15:43:27
【问题描述】:
我想通过求幂绑定两个DoubleProperties。那就是我想做这样的事情:
val1.bindBidirectional(2^val2);
这似乎是不可能的(见docs)。为什么会这样?达到相同结果的最佳方法是什么?是不是很聪明地制作了两个ChangeListeners?
谢谢
【问题讨论】:
标签: java javafx bind pow bidirectional
我想通过求幂绑定两个DoubleProperties。那就是我想做这样的事情:
val1.bindBidirectional(2^val2);
这似乎是不可能的(见docs)。为什么会这样?达到相同结果的最佳方法是什么?是不是很聪明地制作了两个ChangeListeners?
谢谢
【问题讨论】:
标签: java javafx bind pow bidirectional
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 在开发此答案时帮助 solve my own issue!
【讨论】: