我知道如何绑定(bind)属性,但是如何绑定(bind)函数的调用?
例如:我有一个指向文件的ObjectProperty
。现在,我想将路径绑定(bind)到其文件夹?如果 ObjectProperty
的值为 C:\\user\Desktop\text.txt
,则绑定(bind)应指向 C:\\user\Desktop
>.
我想我可以在绑定(bind)中调用 getParentFile()
。
最佳答案
有很多方法可以映射 ObjectProperty
,看看类(class) Bindings
.
(所有示例均假设您有 ObjectProperty<File> file
)
Bindings.createObjectBinding(Callable<T> func, Observable... dependencies)
ObjectBinding<File> parent = Bindings.createObjectBinding(() -> { File f = file.getValue(); return f == null ? null : f.getParentFile(); }, file);
Bindings.select(ObservableValue<?> root, String... steps)
ObjectBinding<File> parent = Bindings.select(file, "parentFile");
当
file
时,这将在错误流上打印警告为空。
您还可以创建自己的映射方法(类似于 createObjectBinding
):
public static <T,R> ObjectBinding<R> map(ObjectProperty<T> property, Function<T,R> function) {
return new ObjectBinding<R>() {
{
bind(property);
}
@Override
protected R computeValue() {
return function.apply(property.getValue());
}
@Override
public void dispose() {
unbind(property);
}
};
}
并使用它
ObjectBinding<File> parent = map(file, f -> f == null ? null : f.getParentFile());
关于javafx - 如何调用绑定(bind)属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167280/