javaif-statementconfirm-dialog

Can I use IF statements with a message dialog in java?


So, I've been stumped on this piece of code for about a week now, I want to have the code sending an error message when the user chooses 'No' or 'Cancel' however I get an error which tells me that NO and CANCEL are not variables. Does anyone have any suggestions as to how I can overcome this problem?

int mc = JOptionPane.QUESTION_MESSAGE;
    int bc = JOptionPane.YES_NO_CANCEL_OPTION;

    int ch = JOptionPane.showConfirmDialog (null, "Select:", "Title", bc, mc);

    if (bc == NO)
    {
        JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
    }
    else if (bc == CANCEL)
    {
        JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
    }
    else
    {
        JOptionPane.showInputDialog("Thank you, you may continue!");
    }

Solution

  • This is all explained in the JOptionPane Javadoc.

    In the code that you've given, the button that you've clicked is identified by the return value from showConfirmDialog, which you've assigned to ch, not bc. In your case, the logic should be

    if (ch == JOptionPane.NO_OPTION) {
        ...
    }
    else if (ch == JOptionPane.CANCEL_OPTION) {
        ...
    }
    else {
        ...
    }