Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 788
JavaMonkey22 Avatar asked Mar 23 '13 01:03

JavaMonkey22


2 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());
like image 82
sarcan Avatar answered Oct 23 '22 20:10

sarcan


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.

like image 1
rolve Avatar answered Oct 23 '22 21:10

rolve