Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind TextField to ReadOnlyDoubleProperty

Tags:

java

javafx

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?

like image 971
kerner1000 Avatar asked Feb 02 '18 10:02

kerner1000


2 Answers

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());
    }
});
like image 51
James_D Avatar answered Oct 13 '22 12:10

James_D


There is an another form of a simple unidirectional binding:

textField.textProperty().bind(someDoubleProperty.asString());
like image 42
oshatrk Avatar answered Oct 13 '22 13:10

oshatrk