Reputation: 10253
Suppose I have two properties and I want to bind a 3rd to be equal to a calculation between them.
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)
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());
}
}
Output:
16.0
16.0
So this seems to bind correctly initially, but result
is not updated when either val1
or factor
is changed.
How do I properly bind this calculation?
Upvotes: 1
Views: 1894
Reputation: 6188
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));
Upvotes: 6