Search code examples
javaswingjoptionpane

JOptionPane / Input Dialog


I try to get an input from the user with this :

int myNumber = Integer.parseInt((String) JOptionPane.showInputDialog(
                            frame,
                            "Number you want:\n",
                            "Enter number",
                            JOptionPane.PLAIN_MESSAGE,
                            null,
                            null,
                            "5"));

It works well but I'm not sure that the user will enter an number in the field and I don't want a NumberFormatException to be thrown.

Is there a way to set a formatter to the JOptionPane (like we can for a text field with a JFormattedTextField with setting a DecimalFormat) ?


Solution

  • Short answer: No, there is no way to do it. JOptionPane doesn't provide any means to validate its input before it closes.

    One easy way around this is to use a JSpinner. JOptionPane allows components and arrays to be used as message objects, so you can do something like this:

    int min = 1;
    int max = 10;
    int initial = 5;
    
    JSpinner inputField =
        new JSpinner(new SpinnerNumberModel(initial, min, max, 1));
    
    int response = JOptionPane.showOptionDialog(frame,
        new Object[] { "Number you want:\n", inputField },
        "Enter number",
        JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.PLAIN_MESSAGE,
        null, null, null);
    
    if (response == JOptionPane.OK_OPTION) {
        int myNumber = (Integer) inputField.getValue();
        // Do stuff with myNumber here
    } else {
        System.out.println("User canceled dialog.");
    }
    

    You can also, as you suggested, pass a JFormattedTextField as a message object instead of a JSpinner.