5

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

Beef
  • 1,413
  • 6
  • 21
  • 36

4 Answers4

11

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);
Blueriver
  • 3,212
  • 3
  • 16
  • 33
Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
4

See How to Use Formatted Text Fields.

If you don't want to use a formatted text field then you should be using an InputVerifier, not a FocusListener.

You can also use a DocumentFilter to filter text as it is typed.

camickr
  • 321,443
  • 19
  • 166
  • 288
2
public void focusLost(FocusEvent fe) {
  String text = this.getText();
  try {
    double d = Double.parseDouble(text); 
    // or Integer.parseInt(text), etc.
    // OK, valid number.
  } catch (NumberFormatException nfe) {
    // Not a number.
  }
}
maerics
  • 151,642
  • 46
  • 269
  • 291
0

I think the best way is to use the KeyTyped listener for JTextField and check if you want your users typed only numbers. Here is a piece of code:

private void jTextField5KeyTyped(java.awt.event.KeyEvent evt) {                                     
         //KEY TYPE FOR AGE
         char c = evt.getKeyChar();
       if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACKSPACE) || c==KeyEvent.VK_DELETE)) {
           getToolkit().beep();
          evt.consume();
       }
    }
Dennis
  • 101
  • 2
  • 10