JOptionPane cancel button

MikeSHR picture MikeSHR · Jun 3, 2013 · Viewed 16.1k times · Source

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; 
    }
}

Answer

A-SM picture A-SM · Jun 3, 2013

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