你打电话时:
Bindings.bindBidirectional(propertyA, propertyB);
的值propertyA
将设置为 的值propertyB
。
所以在这种情况下,正如propertyB
已经提到的ObjectB
,在调用之后,两个属性都将引用:ObjectB
测试代码
import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
public class HellBound {
public static void main(String[] args) {
ObjectProperty<Object> propertyA = new SimpleObjectProperty<>();
ObjectProperty<Object> propertyB = new SimpleObjectProperty<>();
propertyA.set(new ObjectA());
propertyB.set(new ObjectB());
Bindings.bindBidirectional(propertyA, propertyB);
System.out.println("propertyA = " + propertyA);
System.out.println("propertyB = " + propertyB);
}
private static class ObjectA {
}
private static class ObjectB {
}
}
测试输出
propertyA = ObjectProperty [值:appCC.xyzzy.HellBound$ObjectB@7c3df479]
propertyB = ObjectProperty [值:appCC.xyzzy.HellBound$ObjectB@7c3df479]
绑定实现源码
注意电话property1.setValue(property2.getValue());
:
public static <T> BidirectionalBinding bind(Property<T> property1, Property<T> property2) {
checkParameters(property1, property2);
final BidirectionalBinding binding =
((property1 instanceof DoubleProperty) && (property2 instanceof DoubleProperty)) ?
new BidirectionalDoubleBinding((DoubleProperty) property1, (DoubleProperty) property2)
: ((property1 instanceof FloatProperty) && (property2 instanceof FloatProperty)) ?
new BidirectionalFloatBinding((FloatProperty) property1, (FloatProperty) property2)
: ((property1 instanceof IntegerProperty) && (property2 instanceof IntegerProperty)) ?
new BidirectionalIntegerBinding((IntegerProperty) property1, (IntegerProperty) property2)
: ((property1 instanceof LongProperty) && (property2 instanceof LongProperty)) ?
new BidirectionalLongBinding((LongProperty) property1, (LongProperty) property2)
: ((property1 instanceof BooleanProperty) && (property2 instanceof BooleanProperty)) ?
new BidirectionalBooleanBinding((BooleanProperty) property1, (BooleanProperty) property2)
: new TypedGenericBidirectionalBinding<T>(property1, property2);
property1.setValue(property2.getValue());
property1.addListener(binding);
property2.addListener(binding);
return binding;
}
其他问题的答案
我只是想知道为什么 javadoc 没有告诉我们这种有用的信息。
因为javadoc是人写的,不是神写的。有时,人类会做出深不可测的遗漏。也许神也会这样做:-)
我同意应该在 Javadoc 中提供有用的信息。
可以提交错误报告以改进文档 ( http://bugreport.java.com )。或者,在openjfx-dev开发者列表中的帖子可能会获得具有提交权限的开发者来改进它。您可以自己提交补丁,但是对于大多数人来说,除非他们已经是签署了OCA的 JDK 提交者,否则这可能不值得。
我假设这对于 ObservableLists 也应该是相同的,这样 Bindings.bindContentBidirectional() 应该以相同的方式工作吗?
是的,该方法的源代码如下:
list1.setAll(list2);