javaswingjbuttonjoptionpane

How to handle cancel button in JOptionPane


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?


Solution

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