Search code examples
javajtextfieldvalidation

Check if a JTextField is a number


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


Solution

  • 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);