0

I have a JTextField which users must enter a number in that.

I want to check the value to be sure that it contains an **Integer*.*

Here is the code:

JTextField Tex_amount=new JTextField();
.
.
.
String s=Tex_amount.getText(); 
int a=Integer.parseInt(s);

The problem is if the user enter a String in the field i will face with the error: java.lang.NumberFormatException. So how can i check the value?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sal-laS
  • 11,016
  • 25
  • 99
  • 169

2 Answers2

7

there are three ways

  1. use JFormattedTextField with Number Formatter

  2. use JSpinner with SpinnerNumberModel

  3. add DocumentFilter to plain JTextField

mKorbel
  • 109,525
  • 20
  • 134
  • 319
3

You can use try..catch

try{
    int a = Integer.parseInt(s);
}
catch(ArithmeticException e){
    //Handel error here 
}
commit
  • 4,777
  • 15
  • 43
  • 70