Give a Yes/No option in a Java GUI

13,469

Solution 1

Use showConfirmDialog as follows:

int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to close?", "Close?",  JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
   System.exit(0);
}

Solution 2

Look at the docs. There is a JOptionPane.YES_NO_OPTION which you can pass as a parameter.

Solution 3

public static int showConfirmDialog(Component parentComponent,
                                    Object message,
                                    String title,
                                    int optionType)

With an optionType of JOptionPane.YES_NO_OPTION

Share:
13,469
Eric
Author by

Eric

Updated on June 28, 2022

Comments

  • Eric
    Eric almost 2 years

    I'd like to change the code below to present a yes or no option when a user clicks on 'X' but I'm afraid my java newbie skills don't stretch to it yet. Any suggestions please? I'd like to keep the code below as intact as possible in order to see what needs to be done differently for future reference.

    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    
    public class WindowExit extends WindowAdapter
    {
    public void windowClosing(WindowEvent e)
    {
        JOptionPane.showMessageDialog( null, "Are you sure you want to close?" );
        System.exit(0);
    }
    }