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

4

5

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.

Lois answered 22/1, 2013 at 20:58 Comment(0)
L
1

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

Lois answered 23/1, 2013 at 6:36 Comment(1)
I wouldn't recommend that, because you are relying on a specific default locale. If you use the program on a computer with a different locale you'll get different separators ('.' for germany, ' ' for french, etc.). The linked question contains better answers!Whore
U
11

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.

Uncovenanted answered 29/5, 2015 at 14:44 Comment(0)
L
1

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

Lois answered 23/1, 2013 at 6:36 Comment(1)
I wouldn't recommend that, because you are relying on a specific default locale. If you use the program on a computer with a different locale you'll get different separators ('.' for germany, ' ' for french, etc.). The linked question contains better answers!Whore
S
0

You can do it in (at least) 2 ways:

  • Using a keyListener
  • Using DocumentFilter

if you want to use KeyListener:

KeyListener listener = new KeyAdapter(){
    public void keyTyped(KeyEvent e){
        if(e.getKeyCode()<KeyEvent.VK_0||e.getKeyCode()>KeyEvent.VK_9{//input<'0' or input>'9'?
            e.consume();//delete the typed char
        }
    }
}

yourTextField.addKeyListener(listener);

to use the DocumentFilter check this link: How to allow introducing only digits in jTextField?

EDIT: i forgot to say this. As MadProgrammer said in the first comment to this answer, KeyListener is not the proper way to do it, because

You do not know in what order KeyListeners will be notified of the event and the key may have already gone to the text component before it reaches you (or it could have been consumed before it reaches you)

EDIT #2: ANOTHER QUICK WAY

MaskFormatter formatter = new MaskFormatter("#####");
JFormattedTextField field = new JFormattedTextField(formatter);

And the trick should be done. with this you can insert up to 5 digits in tour textfield, more '#' in the string parameter for the formatter = more digits can be typed by the user

Synaesthesia answered 22/1, 2013 at 21:4 Comment(2)
NEVER modify a text component through the use of a KeyListener. You do not know in what order KeyListeners will be notified of the event and the key may have already gone to the text component before it reaches you (or it could have been consumed before it reaches you). However, +1 for the document filterLogography
I tried MaskFormatter , But I must type the number of Digits exactly e.g;"####" will not accept less than 1000, I want to accept less than this numer. How to do it? ThanksLois
F
0

Try this, This is a complete solution for creating and validating number JTextField

NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);//Remove comma from number greater than 4 digit
NumberFormatter sleepFormatter = new NumberFormatter(format);
sleepFormatter.setValueClass(Integer.class);
sleepFormatter.setMinimum(0);
sleepFormatter.setMaximum(3600);
sleepFormatter.setAllowsInvalid(false);

sleepFormatter.setCommitsOnValidEdit(true);// committ value on each keystroke instead of focus lost

JFormattedTextField textFieldSleep = new JFormattedTextField(sleepFormatter);
textFieldSleep.setText("0");
Footplate answered 14/2, 2019 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.