gpt4 book ai didi

JavaFx 8 双向绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 08:58:16 27 4
gpt4 key购买 nike

以下代码触发 java.lang.RuntimeException:无法设置绑定(bind)值:

public class Test {

public static void main( String[] args ) {
final DoubleProperty amount = new SimpleDoubleProperty( 100_000.00 );
final DoubleProperty rate = new SimpleDoubleProperty();
final DoubleProperty part = new SimpleDoubleProperty();
rate.bind( part.divide ( amount.getValue()));
part.bind( rate.multiply( amount.getValue()));
rate.set( 0.025 );//<<----------------------------------- Here is the cause
System.out.println( "Part: " + part.get());
part.set( 1200 );
System.out.println( "Rate: " + rate.get());
}
}

使用 Bindings.bindBidirectional可能是一个解决方案,但我不知道如何。

最佳答案

一个可能的解决方案是创建 InvalidationListeners - 不使用绑定(bind)。

工作原理:

  • 设置费率会导致费率无效。这是设置部分的时间,因此也是无效的。
  • 依次设置速率不会再次触发 InvalidationListener。这就是它的定义方式。

.

public static void main(String[] args) {
final DoubleProperty amount = new SimpleDoubleProperty(100_000.00);
final DoubleProperty part = new SimpleDoubleProperty();
final DoubleProperty rate = new SimpleDoubleProperty();

part.addListener(new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
System.out.println("part is invalid");
rate.set(part.get() / amount.get());
}
});

rate.addListener(new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
System.out.println("rate is invalid");
part.set(rate.get() * amount.get());
}
});

System.out.println("setting rate");
rate.set(0.025);
System.out.println("Part: " + part.get()); //2500

System.out.println("setting part");
part.set(1200);
System.out.println("Rate: " + rate.get()); //0.012
}

上面代码的输出是:

setting rate
rate is invalid
part is invalid
Part: 2500.0
setting part
part is invalid
rate is invalid
Rate: 0.012

关于JavaFx 8 双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com