用户点击"取消"退出循环或完成允许的尝试次数

时间:2016-11-28 04:53:48

标签: java loops if-statement while-loop joptionpane

我想编写一个循环,当用户用完三次尝试,点击取消或用红色x关闭窗口时,循环结束。红色x和用完三个尝试部分工作正常。但是取消按钮没用,并且与OK按钮的作用相同。

我写了一个if语句,但它无效。即使用户按下取消,也会弹出提示用户输入密码的窗口,直到所有允许的尝试都用完为止。这就是我到目前为止所做的:

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

2 个答案:

答案 0 :(得分:0)

1-)你应该在while循环中增加尝试次数。

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

答案 1 :(得分:0)

使用JOptionPane.YES_NO_CANCEL_OPTION代替JOptionPane.CANCEL_OPTION,这应该可以解决问题。更改后,您的代码将如下所示

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