Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOptionPane Yes or No window

I am trying to create a message with a Yes or No button. Then a window will appear with a certain message that depends on if the user clicked Yes or No.

Here is my code:

public class test{
    public static void main(String[] args){

        //default icon, custom title
        int n = JOptionPane.showConfirmDialog(
            null,
            "Would you like green eggs and ham?",
            "An Inane Question",
            JOptionPane.YES_NO_OPTION);

        if(true){
            JOptionPane.showMessageDialog(null, "HELLO");
        }
        else {
            JOptionPane.showMessageDialog(null, "GOODBYE");
        }

        System.exit(0);
    }
}

Right now it prints HELLO whether or not you press Yes or No. How do I get it to show GOODBYE when the user chooses No?

like image 328
Josh King Avatar asked Dec 06 '11 08:12

Josh King


2 Answers

"if(true)" will always be true and it will never make it to the else. If you want it to work correctly you have to do this:

int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
    JOptionPane.showMessageDialog(null, "HELLO");
} else {
    JOptionPane.showMessageDialog(null, "GOODBYE");
    System.exit(0);
}
like image 94
Michaeldcooney Avatar answered Oct 02 '22 20:10

Michaeldcooney


You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:

YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

From here

like image 42
npinti Avatar answered Oct 02 '22 21:10

npinti