我正在使用NumberFormatter
and JFormattedTextField
,但.getValue()
不会返回与用户看到的相同的值。
我认为输入字符串是使用 NumberFormats 解析方法解析的,并且我从NumberFormat.getNumberInstance();
实际的语言环境中获得了 Numberformat。所以我认为我不能轻易扩展它并编写自己的解析方法?
例如,如果用户键入1234.487
thegetValue()
将返回:
1234.487
但用户将被显示1,234.49
另一个例子,使用NumberFormat.getCurrencyInstance();
. 用户类型1234.487
和getValue()
将返回1234.487
,但用户将被显示$1,234.49
相反,如果 Formatter 无法在不四舍五入的情况下格式化值,我希望生成 ParseException。如果用户类型相同4.35b6
,默认情况下格式化程序将显示4.35
并且值将是4.35
,但我想要 ParseException,因为用户输入了无效值。
这是我尝试过的代码:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
final JFormattedTextField ftf = new JFormattedTextField(nf);
ftf.setValue(new BigDecimal("1234.50"));
// Print the value from ftf
final JTextField txt = new JTextField(12);
txt.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
txt.setText(ftf.getValue().toString());
}
});
如何获得与用户看到的相同的价值?