简体   繁体   中英

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.

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM