简体   繁体   English

JavaFX属性绑定

[英]JavaFX Property Binding

How do I bind two DoubleProperties so that one is always the numerically opposite value of the other? 如何绑定两个DoubleProperties,使得一个总是与另一个的数值相反? 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 . 据我所知,在这个特定的用例中可能没有必要使用guard( updating标志),因为我认为JVM中浮点运算的实现保证了--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. 但是,对于更一般的可逆浮点函数,您应该提供明确的保护,以确保舍入错误不会使您进入无限递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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