Home » Java » JavaFX 2.2: how to bind String to Integer?

JavaFX 2.2: how to bind String to Integer?

Posted by: admin December 28, 2021 Leave a comment


I’m trying the following code but it doesn’t compile:

SimpleIntegerProperty startPageProperty = new SimpleIntegerProperty();

TextField startPageField = new TextField();

    startPageField.textProperty(), startPageProperty, new IntegerStringConverter()

The last static method call does not accept these parameters.


Bindings#bindBidirectional expects a StringConverter[Number], you are providing a StringConverter[Integer]. Though it may not be intuitive, you’ll have to use a NumberStringConverter instead.

                           new NumberStringConverter());


While the previous answer is correct, there is another way to solve this, which works better if you want to format numbers in a specific way (e.g. with thousands separators):

var formatter = new TextFormatter<>(new NumberStringConverter("#,###"));

The advantage of using a TextFormatter is that it will reformat any number entered by the user when the text field loses focus.