Question

Guys Im trying to use the JOptionPane but the cancel button is responding as if I entered a wrong input value and does not exit the programm. Any ideas whould be very useful!

int n = 0, k = 0;

Students stu = new Students();      

while (n <= 0) { 

     try { 
       n = Integer.parseInt(JOptionPane.showInputDialog(stu, "Enter the number of people","Input", JOptionPane.INFORMATION_MESSAGE));

       if (n <= 0) {
        OptionPane.showMessageDialog(stu, "You have given a wrong input!", 
             "Warning", JOptionPane.WARNING_MESSAGE);
       }    
    }

    catch (Exception e) { 
          JOptionPane.showMessageDialog(stu, "You have given a wrong input!",
               "Warning",  JOptionPane.WARNING_MESSAGE);
          n = 0; 
    }
}

No correct solution

OTHER TIPS

Is this what you wanted:

int n;
String code = JOptionPane.showInputDialog(null, 
"Enter the size of the group", 
"Team Combination Finder", 
JOptionPane.INFORMATION_MESSAGE);

if (code == null) {
  System.out.println("This is cancel button");
  System.exit(0);
} else if (code.equalsIgnoreCase("")) {
  System.out.println("This is OK button without input");
} else {
  try {
    n = Integer.parseInt(code);
    if (n <= 0) {
      System.out.println("This is wrong input");
    } else {
      System.out.println("This is right input");
    }
  } catch (Exception e) {
    System.out.println("You must input numeric only");
  }
}

See if it works for you :)

As a side note, I think mispelling JOptionPane (on line 11) should raise exceptions needlessly.

After you have shown the OptionDialog you must use a break statement, in order to break the loop. JOptionPane doesn't know about your loop.

Or use

System.exit(ErrorCode);

instead of a break;

update

So I think what you want is this:

String input = JOptionPane.showInputDialog(null, "Enter name :  ", "New Record!", 

while (n <= 0) { 
 try {
   String input = JOptionPane.showInputDialog(stu, "Enter the number of people","Input", JOptionPane.INFORMATION_MESSAGE);
   if(input == null || input.length() == 0)
   {
    OptionPane.showMessageDialog(stu, "You have given a wrong input!", 
         "Warning", JOptionPane.WARNING_MESSAGE);
      System.exit(0);
   }

   n = Integer.parseInt(input);

   if (n <= 0) {
    OptionPane.showMessageDialog(stu, "You have given a wrong input!", 
         "Warning", JOptionPane.WARNING_MESSAGE);
   }    
}

catch (Exception e) { 
      JOptionPane.showMessageDialog(stu, "You have given a wrong input!",
           "Warning",  JOptionPane.WARNING_MESSAGE);
      n = 0; 
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top