javaswingintegernumber-formattingjformattedtextfield

How to make JFormattedTextField accept integer without decimal point (comma)?


I used JFormattedTextField withNumberFormat in this way:

-Creat a JFormattedTextField refernce

JFormattedTextField integerField;

-Create a NumberFormat refernce

NumberFormat integerFieldFormatter;

-In the constructor:

integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setMaximumFractionDigits(0);

integerField = new JFormattedTextField(integerFieldFormatter );
integerField.setColumns(5);

..........

I meant to use it with integer numbers only, but when I type numbers like 1500 it is converted after losing focus to 1,500 , and exception thrown this is the first line of it:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1,500"

When I use JTextField instead of JFormattedTextField All integers accepted normally, But the reason why I want to use JFormattedTextField is to benefit from its input restriction advantages.


Solution

  • I discovered the solution to my problem; Here it is:

    The exact problem is that when I use JFormattedTextField with NumberFormat, the JFormattedTextField adds comma ',' before any next 3 digits for example

    1000 rendered as 1,000

    10000 rendered as 10,000

    1000000 rendered as 1,000,000

    When I read an integer value from JFormattedTextField usign this line of code

      int intValue = Integer.parseInt(integerField.getText());
    

    The comma is read as part of the string; 1000 read as 1,000 and this string value cannot be converted to integer value, and so exception is thrown.

    Honestly the solution is in this Answer but I will repeat it here

    use str.replaceAll(",","")

     int intValue = Integer.parseInt(integerField.getText().replaceAll(",", ""));
    

    This will replace any comma charachter ',' in the returned string and will be converted normally to int as expected.

    Regards