Check if a JTextField is a number

Beef picture Beef · Aug 1, 2011 · Viewed 39.4k times · Source

quick question: I have a JTextField for user input, in my focus listener, when the JTextField loses focus, how can I check that the data in the JTextField is a number? thanks

Answer

Oscar Gomez picture Oscar Gomez · Aug 1, 2011

Try performing Integer.parseInt(yourString) and if it throws a NumberFormatException you'll know the string isn't a valid integer

try {
     Integer.parseInt(myString);
     System.out.println("An integer"):
}
catch (NumberFormatException e) {
     //Not an integer
}

Another alternative is Regex:

boolean isInteger = Pattern.matches("^\d*$", myString);