gpt4 book ai didi

Javafx TextFormatter 退格问题

转载 作者:行者123 更新时间:2023-12-02 02:32:06 25 4
gpt4 key购买 nike

我正在使用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

任何帮助将不胜感激。谢谢!

最佳答案

来自documentation of TextFormatter.getFilter() :

The filter itself is an UnaryOperator that accepts TextFormatter.Change object. It should return a TextFormatter.Change object that contains the actual (filtered) change. Returning null rejects the change.

如果文本没有数字,则无法对其进行解析,在这种情况下您将返回 null,从而导致键入更改被拒绝。

一个选择是简化您的 TextFormatter:

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

关于Javafx TextFormatter 退格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com