Frage

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.

War es hilfreich?

Lösung 2

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

Andere Tipps

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.

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

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");
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top