6

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?

kerner1000
  • 3,382
  • 1
  • 37
  • 57
  • A bidirectional binding is a statement that both properties will always have the same value. If either property is changed, then the other property is automatically changed to match it. This works by the binding calling the properties' `set()` methods as needed. A `ReadOnlyProperty` is, by definition, a property that cannot be changed externally. So there is no way to bidirectionally bind to a `ReadOnlyProperty` because the binding wouldn't have a way to change that property (it has no `set()` method for the binding to call). – James_D Feb 02 '18 at 14:40

2 Answers2

8

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());
    }
});
James_D
  • 201,275
  • 16
  • 291
  • 322
2

There is an another form of a simple unidirectional binding:

textField.textProperty().bind(someDoubleProperty.asString());
oshatrk
  • 499
  • 3
  • 14