0

I want to code a loop that ends when the user has used up their three tries, clicks cancel or closes the window with the red x. The red x and using up the three tries portion work fine. But the cancel button is being useless and acting the same as the OK button.

I have written an if statement but it is ineffective. The window that prompts the user for a password continues to pop up until all allowed attempts are used up even when the user presses cancel. This is what I have so far:

    String[] options = new String[]{"OK", "Cancel"};

    int tries = 0;

    String passString = "";

    int option = JOptionPane.OK_OPTION;

    while (!isValidPassword(passString) && tries < 3) {

            option = JOptionPane.showOptionDialog(null, panel, "The title",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, options, options[1]);


            if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
                break;
            }
Jason_Silva
  • 127
  • 3
  • 13

2 Answers2

0

1-)You should increase the tries in while loop.

String[] options = new String[]{"OK", "Cancel"};

int tries = 0;

String passString = "";

int option = JOptionPane.OK_OPTION;

while (!isValidPassword(passString) && tries < 3) {

    option = JOptionPane.showOptionDialog(null, panel, "The title",
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
        null, options, options[1]);

    tries++;

    if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
        break;
    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Maestus
  • 13
  • 6
  • Where did this i come from? I don't have an i in my while loop. – Jason_Silva Nov 28 '16 at 05:13
  • I did increase the tries I just forgot to include it in the post because I didn't copy and paste correctly. My issue is mostly with the if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) statement. It does not work, when the user clicks cancel the loop still continues and the dialog boxes continue to pop up. – Jason_Silva Nov 28 '16 at 05:23
  • @Jason_Silva you can check this topic http://stackoverflow.com/questions/16367242/ask-user-if-wants-to-quit-via-joptionpane – Maestus Nov 28 '16 at 05:37
0

Use the JOptionPane.YES_NO_CANCEL_OPTION instead of JOptionPane.CANCEL_OPTION and this should fix the issue. After the change your code would be like below

String[] options = new String[]{"OK", "Cancel"};

int tries = 0;

String passString = "";

int option = JOptionPane.OK_OPTION;

while (!isValidPassword(passString) && tries < 3) {

        option = JOptionPane.showOptionDialog(null, panel, "The title",
        JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
        null, options, options[1]);


        if (option == JOptionPane.YES_NO_CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
            break;
        }
Faiz
  • 51
  • 2