Check if 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 verify that the data in the JTextField is a number? thanks

+5
source share
4 answers

Try executing Integer.parseInt(yourString) , and if he chooses a NumberFormatException , you will find out that the string is not 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); 
+9
source

See How to use formatted text fields .

If you do not want to use a formatted text field, you should use an InputVerifier, not a FocusListener.

You can also use DocumentFilter to filter text as you type.

+3
source
 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. } } 
+2
source

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

 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(); } } 
0
source

All Articles