我最近在我的JavaFX应用程序中编写了这样的函数:
public static <T1, T2> void bindAndSet(ReadOnlyProperty<T1> sourceProperty, Property<T2> targetProperty, Function<T1, T2> converter) {
sourceProperty.addListener(new WeakChangeListener<>((obs, oldVal, newVal) -> targetProperty.setValue(converter.apply(newVal))));
targetProperty.setValue(converter.apply(sourceProperty.getValue()));
}
这是带有转换和设置初始值的单向绑定。我在JavaFX方面有一点经验,但它似乎应该是使用绑定的应用程序中相当常见的一部分。Property#bind
似乎几乎没用。它不允许转换类型,并且从检查源代码来看,它不设置初始值。
是否有一个(或2个)方法提供这样的功能?或者也许我使用JavaFX API在一个错误的方式?
您可以使用Bindings.createObjectBinding()
:
targetProperty.bind(Bindings.createObjectBinding(
() -> converter.apply(sourceProperty.get()), sourceProperty));