Search code examples
javauser-interfacejoptionpane

Validating user input in JOptionPane.ShowInputDialog


Using JOptionPane.ShowInputDialog, I need to check if the user inputs an int, otherwise, JOptionPane should return an error message and prompt the user to enter the correct data type.

At the same time, if the user clicks to cancel the program should return to the main menu.

String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
if(weight == null) {
    menuGUI();
} else {
    setWeight(Integer.valueOf(weight));
}

Any suggestions on how I could do this?


Solution

  • Use while loop

    Integer w = null;
    while (true) {
        String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
        if (weight == null) {
            break;
        }
    
        try {
            w = Integer.parseInt(weight);
            break;
        } catch (NumberFormatException e) { 
            JOptionPane.showMessageDialog(null, "Enter a valid integer", "error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    if (w == null) { //The user clicked cancel
        menuGUI();
    } else { //Do what you want with w
    }