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,107
  • 18
  • 130
  • 305
Sal-laS
  • 10,023
  • 25
  • 90
  • 156

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,107
  • 18
  • 130
  • 305
3

You can use try..catch

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