Не совсем. Вы можете использовать пользовательский конвертер, который просто выводит значение по умолчанию, если синтаксический анализ завершается неудачно:
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);
В качестве альтернативы используйте TextFormatter
, который фиксирует только на Введите и потерю фокуса и автоматически устанавливает значение по умолчанию, если не удается проанализировать строку:
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());