Jai
Jai

Reputation: 8363

JavaFX: Bind bidirectional with NumberConverter

Consider this:

final TextField tfNum = new TextField();
final IntegerProperty intProp = new SimpleIntegerProperty();

Bindings.bindBidirectional(tfNum.textProperty(), intProp,
    new javafx.util.converter.NumberStringConverter());

When the user types in -1, the binding throws exception when the user types in the first character -. Is there a way to make the NumberStringConverter handle this gracefully?

Upvotes: 1

Views: 1423

Answers (1)

fabian
fabian

Reputation: 82491

Not really. You could use a custom converter though that simply outputs a default value, if parsing fails:

TextField tf = new TextField();
StringConverter<Number> converter = new StringConverter<Number>() {

    @Override
    public String toString(Number object) {
        return object == null ? "" : object.toString();
    }

    @Override
    public Number fromString(String string) {
        if (string == null) {
            return 0;
        } else {
            try {
                return Integer.parseInt(string);
            } catch (NumberFormatException ex) {
                return 0;
            }
        }
    }

};
IntegerProperty property = new SimpleIntegerProperty();
Bindings.bindBidirectional(tf.textProperty(), property, converter);

Alternatively use a TextFormatter that only commits on Enter and the loss of focus and automatically sets the default value if it fails to parse the string:

TextField tf = new TextField();
StringConverter<Number> converter = new NumberStringConverter();

TextFormatter<Number> formatter = new TextFormatter<>(converter, 0);
tf.setTextFormatter(formatter);

IntegerProperty property = new SimpleIntegerProperty();
property.bindBidirectional(formatter.valueProperty());

Upvotes: 1

Related Questions