Search code examples
javajoptionpane

StringUtils.isNumeric blocks JOptionPane cancel option


This is the code I'm using to process the input of an integer :

public static int getIntInput(String message) {
    String numberStr = JOptionPane.showInputDialog(message);
    while (!StringUtils.isNumeric(numberStr) || Integer.parseInt(numberStr) == 0) {
        numberStr = JOptionPane.showInputDialog(message);
    }
    return Integer.parseInt(numberStr);
}

It works fine, except when I want to press "cancel" or close button on the JOption window. When I do that, the JOptionPane window shows up again.

How can I correctly close a JOptionPane window when the cancel or close button is pushed?


Solution

  • while (!StringUtils.isNumeric(numberStr) || Integer.parseInt(numberStr) == 0) {
    
            if (numberStr == null) {
               return 0; 
            }
            else {
                numberStr = JOptionPane.showInputDialog(message);
            }
    }
    

    This does the trick.