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

后端 未结 4 1562
别跟我提以往
别跟我提以往 2021-01-14 06:58

I used JFormattedTextField withNumberFormat in this way:

-Creat a JFormattedTextField refernce

JFormattedTextF         


        
4条回答
  •  清酒与你
    2021-01-14 07:51

    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

提交回复
热议问题