Reputation: 1035
I know how to bind a property, but how can I bind the call of a fuction?
For example: I have a ObjectProperty
which points to a file. Now, I want to bind the path to its folder? If the value of ObjectProperty
is C:\\user\Desktop\text.txt
, the bonding should point to C:\\user\Desktop
.
I thought I can call getParentFile()
within the binding.
Upvotes: 3
Views: 1460
Reputation:
There a many ways to map an ObjectProperty
, take a look at the class Bindings
.
(All examples assume that you have a 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");
This will print a warning on the error-stream when file
is null.
You can also create your own mapping method (which is similar to 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);
}
};
}
And use it
ObjectBinding<File> parent = map(file, f -> f == null ? null : f.getParentFile());
Upvotes: 5