9

I have a JFormattedTextField with a NumberFormat with Locale.US. So the decimal separator is the point and the grouping separator is the comma.

Now I type the string "1,23" in this text field and move the focus to another component. I would expect the string to disappear (like it does when i type "a" instead of "1,23") because it is obviously not a valid representation of a number when using Locale.US. But instead the text in the text field is changed to "123".

This is because the used NumberFormat is not strict when parsing and simply ignores the comma.

Question: How can I tell NumberFormat to throw a ParseException in this case so the text field will be empty after moving the focus to another component?

Test Code:

JDialog dialog = new JDialog();
JPanel panel = new JPanel(new BorderLayout());
dialog.getContentPane().add(panel);

NumberFormat nf = NumberFormat.getInstance(Locale.US);
JFormattedTextField textField = new JFormattedTextField(nf);
textField.setText("1,23");
panel.add(textField, BorderLayout.CENTER);
panel.add(new JButton("focus"), BorderLayout.EAST);

dialog.pack();
dialog.setVisible(true);

Move the focus from the text field to the button and the text will change to "123".

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
General Martok
  • 175
  • 1
  • 6
  • 1
    This is not a duplicate. The other question was about Integers, not Doubles. The question here boils down to an over-lenient NumberFormat that does not check if a comma at that position is allowed. Looks like we need a subclass of NumberFormat with stricter checking. – Ralf H Jun 11 '15 at 14:53
  • 1
    @RalfH: You are right, this is not a duplicate. I've edited the question to show the underlying use of NumberFormat in the JFormattedTextField. – General Martok Jun 23 '15 at 09:17
  • 1
    How can i get the duplicate label removed from this question? I would like to post my own solution. – General Martok Nov 19 '15 at 14:34
  • 1
    Thanks for reopening the question, but my solution can now be found under https://stackoverflow.com/questions/33808144/jformattedtextfield-with-strict-parsing-number-format. – General Martok Nov 20 '15 at 09:30

2 Answers2

3

I would suggest you to use regex and use the match fucntion like this:

matches("\\d+([.,])?")

Also if you will use Integer.parseInt(String) will throw an exception if it will be parsed or you can use Double.parseDouble(value)

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Actually, Number is just a super class for Double, so you could use Double.parseDouble(...) and then auto-unboxing should do the rest.

Karrde
  • 471
  • 2
  • 9