Javafx TextFormatter Backspacing问题

时间:2017-10-25 19:56:13

标签: java javafx

我使用 javafx.scene.control.TextFormatter 将格式文本字段转换为货币字段。下面显示了我的代码。

private static final double DEFAULT_VALUE = 0.00d;
private static final String CURRENCY_SYMBOL = "Rs"; //
public static final DecimalFormat CURRENCY_DECIMAL_FORMAT
        = new DecimalFormat(CURRENCY_SYMBOL + "###,##0.00");

public static TextFormatter<Double> currencyFormatter() {
    return new TextFormatter<Double>(new StringConverter<Double>() {
        @Override
        public String toString(Double value) {
            return CURRENCY_DECIMAL_FORMAT.format(value);
        }

        @Override
        public Double fromString(String string) {
            try {
                return CURRENCY_DECIMAL_FORMAT.parse(string).doubleValue();
            } catch (ParseException e) {
                return Double.NaN;
            }
        }
    }, DEFAULT_VALUE,
            change -> {
                try {
                    CURRENCY_DECIMAL_FORMAT.parse(change.getControlNewText());
                    return change;
                } catch (ParseException e) {
                    return null;
                }
            }
    );
}

//format textfield into a currency formatted field
text_field.setTextFormatter(SomeClass.currencyFormatter());

一切正常,但我不能退出整个文本域。

enter image description here

任何帮助都会很明显。谢谢!

1 个答案:

答案 0 :(得分:2)

来自documentation of TextFormatter.getFilter()

  

过滤器本身是一个UnaryOperator,它接受​​TextFormatter.Change个对象。它应返回包含实际(已过滤)更改的TextFormatter.Change对象。 返回null会拒绝更改。

如果文本没有数字,则无法解析,在这种情况下,您将返回null,这会导致输入更改被拒绝。

一种选择是简化TextFormatter:

return new TextFormatter<Number>(
    new NumberStringConverter(CURRENCY_DECIMAL_FORMAT));