Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 470
Saleh Feek Avatar asked Jan 22 '13 20:01

Saleh Feek


1 Answers

I realize this is an old question but I just stumbled upon it through the same issue. As the other answers seemed like workarounds to me, I took a closer look at the NumberFormat methods.

I found that the easiest approach would actually be to simply deactivate grouping on the NumberFormat instance:

NumberFormat integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setGroupingUsed(false);

That way no group delimiters will appear in the textfield output.

Of course you will also not be able to use them for your input, but that was not intended by the question, right?

Also for an integer instance of NumberFormat you don't need to explicitly setMaximumFractionDigits(0), as that is part of what getIntegerInstance() does for you.

like image 160
GrafWampula Avatar answered Sep 24 '22 00:09

GrafWampula