我有许多带有数字数据的 JFormattedTextdields。我使用过 DecimalFormat、InternationalFormatter、DocumentListener,还尝试过使用 CaretPositionListener。
我面临的唯一问题是当数字输入增长并且分组字符介于两者之间时插入符号的位置。
如何在 focusGained 和 onFocusLost 上动态设置相应 jformattedtextfields 的 DecimalFormat 的 setGroupingUsed()。
任何想法或建议......
更新代码和问题: 当我尝试输入“12345”时,添加“1234”时会出现逗号“1,234”。这会在 3 和 4 之间而不是在 4 之后出现插入符号。我使用的格式化代码:
DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance();
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
final InternationalFormatter formatter = new InternationalFormatter(numberFormat);
formatter.setAllowsInvalid(false);
formatter.setMinimum(0.00);
formatter.setMaximum(999999999.99);
return formatter;
这就是我在自定义 JFormattedTextField 上实现的解决方案。在输入值时您有没有更好的方法来处理分组字符,所以插入符号位置保持正确:
public void focusGained(FocusEvent e) {
if (numberFormat.isGroupingUsed()) {
Object o = this.getValue();
numberFormat.setGroupingUsed(false);
formatter.setFormat(numberFormat);
this.setFormatterFactory(new AbstractFormatterFactoryImpl());
this.setValue(o);
this.setText(o.toString());
}
}
public void focusLost(FocusEvent e) {
try {
this.commitEdit();
} catch (ParseException ex) {
//Logger.getLogger(NumberFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
}
Object o = this.getValue();
//System.out.println("focusLost : getValue = " + o);
numberFormat.setGroupingUsed(true);
formatter.setFormat(numberFormat);
this.setFormatterFactory(new AbstractFormatterFactoryImpl());
this.setValue(o);
this.setText(o.toString());
//System.out.println("focusLost : Text Set = " + o.toString());
}