Search code examples
javaswingjoptionpane

Recognize that user select Yes Or No in Joptionpane


I have a frame that when user want to delete a record, a warning pane should be displayed.

But, Now i have to recognize that if user select Yes, Then i remove selected row and if select no, Don't remove it!

How?

if (e.getSource() == deleteUser) {
JOptionPane.showConfirmDialog(rootPane, "Are You Sure To Delete?", "Delete User", WIDTH);

// if yes, Then remove
}

Solution

  • From the JavaDocs...

    public static int showConfirmDialog(Component parentComponent,
                        Object message,
                        String title,
                        int optionType)
                                 throws HeadlessException
    
    Brings up a dialog where the number of choices is determined by the optionType parameter.
    
    Parameters:
        parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
        message - the Object to display
        title - the title string for the dialog
        optionType - an int designating the options available on the dialog: YES_NO_OPTION, YES_NO_CANCEL_OPTION, or OK_CANCEL_OPTION
    Returns:
        an int indicating the option selected by the user
    

    The return type will be dependent on the value you pass to the optionType parameter

    This would suggest you should do something like...

    int result = JOptionPane.showConfirmDialog(rootPane, "Are You Sure To Delete?", "Delete User", JOptionPane.YES_NO_OPTION);
    if (result == JOptionPane.YES_OPTION) {
        // Do something here
    }
    

    Have a look at How to make dialogs for more details...