user3103074
user3103074

Reputation: 5

Validate textfield input in GUI

I have two text fields and they must add up to 100 when submit is clicked, if I put in correct values into text field there's no error but if I leave the text field blank or put a letter in it the error handling isn't right. Any ideas?

submit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        if (validation == true) {
            int numA = Integer.parseInt(aTextField.getText());
            int numB = Integer.parseInt(aTextField.getText());
            int sum = numA + numB;

            if (sum == 100) {
                validation = true;
                System.out.println("success");
            } else {
                JOptionPane.showMessageDialog(createFrame, "A and B must add up to 100");
                validation = false;

            }


        }

this is the error

int numA = Integer.parseInt(aTextField.getText());

Upvotes: 0

Views: 1858

Answers (2)

Rudi Kershaw
Rudi Kershaw

Reputation: 12972

Integer.parseInt(str); throws a NumberFormatException (the error you are seeing) if the String parsed into the method can not be converted into a number.

You could use some exception handling in this particular situation. I would suggest a try and catch block. For example;

   try{
       if(validation == true){
            int numA = Integer.parseInt(aTextField.getText());
            int numB = Integer.parseInt(aTextField.getText());
            int sum = numA + numB;

            if(sum == 100){
                validation = true;
                System.out.println("success");
            } else{
                JOptionPane.showMessageDialog(createFrame, "A and B must add up to 100");
                validation = false;
            }
        }
    } catch (NumberFormatException n){
            JOptionPane.showMessageDialog(createFrame, "Only numbers should be entered into A and B");
            validation = false;
    }

If the exception is now thrown from within the try block, it will be 'caught' and then validation will be set to false in the catch block. You could also use the catch block to display a message saying that only numbers should be entered into the fields.

Another way to achieve this using the Swing API is if you don't want them to ever put texts into those fields you could use a JFormattedTextField to allow them to only enter numbers.

I hope this helps. Let me know how you get on.

Upvotes: 1

SebastianH
SebastianH

Reputation: 2182

Check the javadoc of Integer.parseInt! The function cannot handle an empty string. What number should that be anyways?

Possible solutions:

  • set the default text of your textFields to "0"

  • add exception handling for the parseInt calls (you could fall back to 0 or prompt the user to correct)

Upvotes: 0

Related Questions