简体   繁体   中英

JavaFX Property Binding

How do I bind two DoubleProperties so that one is always the numerically opposite value of the other? I'm looking for something along the lines of this, however all working solutions are also acceptable:

DoubleProperty num1 = new SimpleDoubleProperty(5);
DoubleProperty num2 = new SImpleDoubleProperty();
num2.bindBidirectional(num1.negativeProperty());

num2.setValue(-7); // num1.getValue() is now 7
num2.setValue(56); // num1.getValue() is now -56
num1.setValue(256); // num2.getValue() is now -256
num1.setValue(-1004); // num2.getValue() is now 1004

You can use listeners:

private boolean updating ;

// ...

num1.addListener((obs, oldValue, newValue) -> {
    if (! updating) {
        updating = true ;
        num2.set(-newValue);
        updating = false ;
    }
});

num2.addListener((obs, oldValue, newValue) -> {
    if (! updating) {
        updating = true ;
        num1.set(-newValue);
        updating = false ;
    }
});

As far as I understand it, the guard ( updating flag) is probably not necessary in this particular use case, as I think the implementation of floating point arithmetic in the JVM guarantees that --x == x . However, for more general invertible floating-point functions, you should provide an explicit guard to ensure that rounding errors don't send you into infinite recursion.

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