Eric
Eric

Reputation: 35

Give a Yes/No option in a Java GUI

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);
}
}

Upvotes: 3

Views: 14389

Answers (3)

Saurabh
Saurabh

Reputation: 799

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);
}

Upvotes: 11

willcodejavaforfood
willcodejavaforfood

Reputation: 44053

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

With an optionType of JOptionPane.YES_NO_OPTION

Upvotes: 2

Petar Minchev
Petar Minchev

Reputation: 47363

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

Upvotes: 6

Related Questions