I can bind a TextField
's text property to a DoubleProperty
, like this:
textField.textProperty().bindBidirectional(someDoubleProperty, new NumberStringConverter());
But what if my someDoubleProperty
is an instance of ReadOnlyDoubleProperty
instead of DoubleProperty
?
I am acutally not interested in a bidirectional binding. I use this method only because there is no such thing as
textField.textProperty().bind(someDoubleProperty, new NumberStringConverter());
Do I need to use listeners instead or is there a "binding-solution" for that as well?
Is there somthing like
textField.textProperty().bind(someDoubleProperty, new NumberStringConverter());
out there?
For a unidirectional binding, you can do:
textField.textProperty().bind(Bindings.createStringBinding(
() -> Double.toString(someDoubleProperty.get()),
someDoubleProperty));
The first argument is a function generating the string you want. You could use a formatter of your choosing there if you wanted.
The second (and any subsequent) argument(s) are properties to which to bind; i.e. if any of those properties change, the binding will be invalidated (i.e. needs to be recomputed).
Equivalently, you can do
textField.textProperty().bind(new StringBinding() {
{
bind(someDoubleProperty);
}
@Override
protected String computeValue() {
return Double.toString(someDoubleProperty.get());
}
});
There is an another form of a simple unidirectional binding:
textField.textProperty().bind(someDoubleProperty.asString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With