Shahjahan KK
Shahjahan KK

Reputation: 91

How to validate a textfield by checking if its text is integer

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

Answers (4)

Sunil
Sunil

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

Vincent van der Weele
Vincent van der Weele

Reputation: 13177

int x = 0;
try {
    x = Integer.parseInt(textField.getText());
} catch (NumberFormatException e) {
    System.out.println("Not a number");
}

Upvotes: 3

camickr
camickr

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

bjarven
bjarven

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

Related Questions