Rice University logo
Top blue bar image
Boanerges Aleman-Meza, Computer Scientist

Java dialog for yes-no question

Java Dialog for giving user option of YES/NO in a GUI, the default is the second option in this case (i.e., the NO). I’d like to quickly find this code when needed, but also important is how the question needs to be made, and the text of each button needs to be worded so that user can better know what each button is going to do.

String[] options = { "Yes, discard changes", "No, go back to where I was" };
int n = JOptionPane.showOptionDialog( dialog, "Changes have not been saved!\nDiscard Changes?",
        "Unsaved changes", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[ 1 ] );
if( n == 0 ) {
dialog.setVisible( false );

Maybe I could have proposed in this way, but setting the default to ‘YES’. Fun, but my wife likely wont think it is fun, heheh.

Note: the question has a mistake, it should say “Changes have not been saved”

Extra note: simple html can be used, such as

"<html>Yes,<br>discard changes</html>"

One Response to “Java dialog for yes-no question”

  1. Wz says:

    Changes have been made, not “changed”

Leave a Reply