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
Asked
Active
Viewed 4.5k times
4 Answers
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
-
Oops, meant to edit mine not yours, rolled back already, sorry! =| – maerics Aug 01 '11 at 03:25
-
You escaped an semicolon here: `System.out.println("An integer");` – Apopei Andrei Ionut Jul 23 '13 at 15:16
-
2I also believe the `(NumberFormatException)` needs to be `(NumberFormatException e)` – Admin Voter Apr 09 '15 at 16:32
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