让我们考虑三个JavaFX属性:A B C。
现在让我们将它们双向绑定成一个三角形(A-B、B-C、A-C)。
现在让我们假设我们修改了 A 的值。
这是否会导致问题(例如无限递归)?
JavaFX可以处理这样的循环绑定图吗?如果是,它是如何做到的?
感谢您的阅读。
试试看...
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
public class CyclicPropertyTest {
public static void main(String[] args) {
IntegerProperty x = new SimpleIntegerProperty(0);
IntegerProperty y = new SimpleIntegerProperty(1);
IntegerProperty z = new SimpleIntegerProperty(2);
x.addListener((obs, oldValue, newValue) -> System.out.printf("x changed from %d to %d %n", oldValue, newValue));
y.addListener((obs, oldValue, newValue) -> System.out.printf("y changed from %d to %d %n", oldValue, newValue));
z.addListener((obs, oldValue, newValue) -> System.out.printf("z changed from %d to %d %n", oldValue, newValue));
x.bindBidirectional(y);
y.bindBidirectional(z);
z.bindBidirectional(x);
x.set(1);
}
}
仅当属性的值发生更改时,才会通知侦听器。当 x 设置为 1 时,这会导致 y 设置为 1,从而导致 z 设置为 1。这些会激发听众。由于 z 发生了变化,这会导致(至少在概念上)将 x 设置为 1,但由于它已经是 1,因此不会通知侦听器,因此循环终止。