user3102872
user3102872

Reputation: 619

How do i display a confirmation message when the user clicks on the red cross? Java GUI

I'm working on Java and I'm trying to display a confirmation message to the user when he wants to exit but I didn't know where I have to put it exactly. may you help me?

Upvotes: 2

Views: 215

Answers (3)

Add a WindowListner to your JFrame and override windowClosing method and do a pop-up with JOptionPane warning user.

Upvotes: 1

Sachin
Sachin

Reputation: 3554

You can stop frame from closing by default by using WindowConstants.DO_NOTHING_ON_CLOSE as peram to below API

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            /* (non-Javadoc)
             * @see java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent)
             */
            @Override
            public void windowClosing(WindowEvent e) {
                //Use JOptionPane. If everything goes fine 
                                //then do frame.dispose();

            }


        });

Upvotes: 3

Tim B
Tim B

Reputation: 41188

If your exit is being done by pressing the x button on the window then you need to handle the windows events.

To get the confirmation message you need to pop up a JOptionPane.

There is a discussion of a number of ways to handle the window closing here:

How can a Swing WindowListener veto JFrame closing

Documentation on JOptionPane is here:

http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

Upvotes: 2

Related Questions