如何调用绑定方法 属性
How to call method for bind property
我知道如何绑定一个属性,但是我如何绑定一个函数的调用?
例如:我有一个 ObjectProperty
指向一个文件。现在,我想将路径绑定到它的文件夹?如果 ObjectProperty
的值为 C:\user\Desktop\text.txt
,则绑定应指向 C:\user\Desktop
。
我以为我可以在绑定中调用 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());
我知道如何绑定一个属性,但是我如何绑定一个函数的调用?
例如:我有一个 ObjectProperty
指向一个文件。现在,我想将路径绑定到它的文件夹?如果 ObjectProperty
的值为 C:\user\Desktop\text.txt
,则绑定应指向 C:\user\Desktop
。
我以为我可以在绑定中调用 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());