Reputation: 91
I have several text fields in a java Swing application. I want to check if the user entered a valid integer in it or not.
Would you advise me on how can I perform such a validation.
Upvotes: 0
Views: 3510
Reputation: 54
see this code, to make text field accept number character only
//to accept numbers only
@Override
public void keyTyped(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
char inputChar = e.getKeyChar();
if (inputChar >= '0' && inputChar <= '9') {
String text = inetgereTextField.getText() + inputChar;
System.out.println("Number :- " + Integer.parseInt(text));
} else {
e.consume();
}
}
}
Upvotes: 0
Reputation: 13177
int x = 0;
try {
x = Integer.parseInt(textField.getText());
} catch (NumberFormatException e) {
System.out.println("Not a number");
}
Upvotes: 3
Reputation: 324078
If you want to make sure a number was entered, then add a DocumentListener to the Document of the text field to make sure the user only enters numeric digits. Then there is no need to validated later.
Or you can use a JFormattedTextField.
Search the forum for examples as this advice is given all the time.
Upvotes: 4
Reputation: 801
I'd use the Simple Validation API, if you don't mind bringing in additional dependencies.
https://kenai.com/projects/simplevalidation/pages/Home
Upvotes: 1