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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With