JavaMonkey22
JavaMonkey22

Reputation: 871

JavaFX 2.2: how to bind String to Integer?

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.

Upvotes: 5

Views: 8464

Answers (2)

rolve
rolve

Reputation: 10218

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.

Upvotes: 1

sarcan
sarcan

Reputation: 3165

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());

Upvotes: 13

Related Questions