How to handle cancel button in JOptionPane

The showMessageDialog, shouldn't show two buttons, so something is amiss with either your code or your interpretation of it. Regardless, if you want to give the user an choice and want to detect that choice, don't use a showMessageDialog but rather a showConfirmDialog, and get the int returned and test it to see if it is JOptoinPane.OK_OPTION.


For example:

int n = JOptionPane.showConfirmDialog(
                            frame, "Would you like green eggs and ham?",
                            "An Inane Question",
                            JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {

} else if (n == JOptionPane.NO_OPTION) {

} else {

}

Alternatively with showOptionDialog:

Object[] options = {"Yes, please", "No way!"};
int n = JOptionPane.showOptionDialog(frame,
                "Would you like green eggs and ham?",
                "A Silly Question",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);
if (n == JOptionPane.YES_OPTION) {

} else if (n == JOptionPane.NO_OPTION) {

} else {

}

See How to Make Dialogs for more details.

EDIT: showInputDialog

String response = JOptionPane.showInputDialog(owner, "Input:", "");
if ((response != null) && (response.length() > 0)) {

}

This is an old question, and I am an Java newbie so there might be better solutions, but I wanted to know the same, and maybe it can help others, what I did was to check if the response was null.

If the user clicks "cancel", the response will be null. If they click "ok" without entering any text the response will be the empty string.

This worked for me:

//inputdialog 
    JOptionPane inpOption = new JOptionPane();

    //Shows a inputdialog
    String strDialogResponse = inpOption.showInputDialog("Enter a number: "); 

    //if OK is pushed then (if not strDialogResponse is null)
    if (strDialogResponse != null){

        (Code to do something if the user push OK)  

    }
    //If cancel button is pressed
    else{

        (Code to do something if the user push Cancel)

    }