How to handle cancel button in JOptionPane

Mazzy picture Mazzy · Jul 15, 2012 · Viewed 69.2k times · Source

I had created a JOptionPane of type showInputDialog. When it opens it, it shows me two buttons: OK and Cancel. I would like to handle the action when I push on Cancel button, but I don't know how to reach it. How can I get it?

Answer

tenorsax picture tenorsax · Jul 15, 2012

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)) {

}