I'm using a NumberFormatter
and JFormattedTextField
, but the .getValue()
doesn't return the same value as the user is seeing.
I think the input-string is parsed using NumberFormats parse-method, and I get the Numberformat from NumberFormat.getNumberInstance();
with the actual Locale. So I don't think I easily can extend it and write my own parse-method?
In example, if the user types 1234.487
the getValue()
will return:
1234.487
but the user will be displayed 1,234.49
Another example, using NumberFormat.getCurrencyInstance();
. The user types 1234.487
and the getValue()
will return 1234.487
but the user will be displayed $1,234.49
Instead, I want an ParseException be generated if the Formatter can't format the value without rounding. Same thing if the user types 4.35b6
, by default the formatter will display 4.35
and the value will be 4.35
, but I want a ParseException, because the user typed in an invalid value.
Here is the code that I have tried with:
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());
}
});
How to get the same value as the user is seeing?