AlecR
AlecR

Reputation: 57

Getting good input from a JOptionPane

I'm trying to get a user to enter an integer into a JOptionPane, and need a way to make sure the user inputs an integer. Could I use a while loop for this, and if so how do I implement this?

Upvotes: 0

Views: 42

Answers (3)

Suspended
Suspended

Reputation: 1190

You could do something like this:

boolean taken = false;
int myInteger = 0;
while(!taken){
   String s = (String)JOptionPane.showInputDialog(this, "Your question", "Your window title", JOptionPane.PLAIN_MESSAGE, null, null, "");

   //Check if input is an integer
   try{
      myInteger = Integer.parseInt(s);
      taken = true;
   catch(NumberFormatException e){
      taken = false;
   }
}

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347204

There are a number of ways you might achieve this, my personal preference is to take control over what the user can enter, for example, using a JSpinner...

JPanel questionPanel = new JPanel();
questionPanel.add(new JLabel("Place enter a number:"));
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 5));
questionPanel.add(spinner);
Integer result = null;
int exitValue = JOptionPane.OK_OPTION;
do {
    exitValue = JOptionPane.showConfirmDialog(null, questionPanel, "Guess", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    result = (Integer) spinner.getValue();
} while (result == null && exitValue != JOptionPane.CANCEL_OPTION);

Upvotes: 0

Mohammed Housseyn Taleb
Mohammed Housseyn Taleb

Reputation: 1828

in a loop : use a try-catch statement for a MalFormedNumeberException in the try you use the JOptionPane to get input trim the use the parse from the Integer class then if success a break in the catch: print the exception using printStackTrace method or show message that inform user to input valid number format

     while(true){
        try{
                 //here the JOptionPane input
                 //here the parseInt from Integer class
                 break;
            }catch(NumberFormatException e){
                 //JOptionPane with show message dialogue asking for valide input
            }
       }

Upvotes: 0

Related Questions