I didn't find any java question that helped me solve my problem, so here I come.
I'm currently trying to use a NumberFormatter with a JFormattedTextField to format a price in a GUI as the user types it in.
But I'm getting strange results after typing 2 digits in the textfield.
Here the code I use to test (Netbeans 8.0 + JDK 1.7.0_51):
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
symbols.setCurrencySymbol("EUR");
DecimalFormat format = new DecimalFormat("¤ #,##0.00", symbols);
format.setMaximumFractionDigits(2);
format.setGroupingUsed(true);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setMinimum( 0.00);
formatter.setMaximum(9_999.99);
formatter.setAllowsInvalid(false);
formatter.setOverwriteMode(true);
JFormattedTextField field = new JFormattedTextField(formatter);
field.setColumns(10);
field.setValue(0.33);
frame.add(field);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
What I expect :
// Step Text in TextField
// 1: GUI started EUR <caret>0.33
// 2: '1' pressed EUR 1<caret>.33
// 3: '2' pressed EUR 12<caret>.33
What I get :
// Step Text in TextField
// 1: start GUI EUR <caret>0.33 [OK]
// 2: press '1' EUR 1<caret>.33 [OK]
// 3: press '2' EUR 1 2<caret>33.00 [NOK, see expected result above]
To me it looks like the Formatter does (for step 3) :
- insert '2' at the caret position -> EUR 12.33
- remove all 'formatting characters' -> 1233
- Formats the result of the "removal" again -> EUR 1 233.00
Is this the default behavior for the NumberFormatter? If yes, am I missing something in the setup of the formatter or do I need to write a custom one? If not, what am I doing wrong?
Regards,
Xan.