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

Questions:

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

SimpleIntegerProperty startPageProperty = new SimpleIntegerProperty();

TextField startPageField = new TextField();

Bindings.bindBidirectional(
    startPageField.textProperty(), startPageProperty, new IntegerStringConverter()
);

The last static method call does not accept these parameters.

Answers:

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.

Bindings.bindBidirectional(startPageField.textProperty(), 
                           startPageProperty, 
                           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("#,###"));
formatter.valueProperty().bindBidirectional(startPageProperty);
startPageField.setTextFormatter(formatter);

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