user2336315
user2336315

Reputation: 16067

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) ?

Upvotes: 2

Views: 1370

Answers (3)

vcque
vcque

Reputation: 31

What about giving the JFormattedTextField you want to your dialog ?

    JFormattedTextField field = new JFormattedTextField(DecimalFormat.getInstance());
    JOptionPane.showMessageDialog(null, field);
    System.out.println(field.getText());

You can also use a more elaborate component if it fits you better.

Upvotes: 1

VGR
VGR

Reputation: 44413

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.

Upvotes: 2

camickr
camickr

Reputation: 324207

See the Swing tutorial on Stopping Automatic Dialog Closing for a way to edit the value.

Or Check out the JOptionPane API. Maybe use:

showConfirmDialog(Component parentComponent, Object message, String title, int optionType) 

The message can be a Swing component.

Upvotes: 1

Related Questions