如何将值绑定到计算结果? [英] How to bind a value to the result of a calculation?
问题描述
假设我有两个属性,我想绑定一个第三个等于它们之间的计算。
Suppose I have two properties and I want to bind a 3rd to be equal to a calculation between them.
在这个例子中,我有一个 val1
和 factor
属性。我希望结果
属性绑定到两者的幂: result = Math.pow(factor,val1)
In this example, I have a val1
and a factor
property. I want the result
property to be bound to the "power" of the two: result = Math.pow(factor, val1)
以下MCVE显示了我目前正在尝试这样做的方式,但它没有被正确绑定。
The following MCVE shows how I am currently attempting to do so, but it is not being bound properly.
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
或因素时,
已更改。结果
不会更新
So this seems to bind correctly initially, but result
is not updated when either val1
or factor
is changed.
如何正确绑定此计算?
推荐答案
Callable< Double> ,表示绑定依赖关系的 Observable
的变量。只有在列出的某个依赖项发生更改时,才会更新绑定。由于您未指定任何内容,因此绑定在创建后永远不会更新。
The Bindings.createDoubleBinding
method takes, in addition to its Callable<Double>
, a vararg of Observable
representing the dependencies of the binding. The binding only gets updated when one of the listed dependencies is altered. Since you did not specify any, the binding never gets updated after being created.
要更正您的问题,请使用:
To correct your issue, use:
result.bind(Bindings.createDoubleBinding(
() -> Math.pow(factor.get(), val1.get()),
val1,
factor));
这篇关于如何将值绑定到计算结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!