2

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?

Sachin
  • 3,424
  • 3
  • 21
  • 42
user3102872
  • 529
  • 2
  • 5
  • 9

3 Answers3

3

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

            }


        });
Sachin
  • 3,424
  • 3
  • 21
  • 42
2

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

Community
  • 1
  • 1
Tim B
  • 40,716
  • 16
  • 83
  • 128
  • The thing i didn't get is that: is it a method a have to create or a variable? it doesn't seem clear :\ Thank you, btw – user3102872 Dec 17 '13 at 14:25
  • A method. Methods do things, variables store data. (Sometimes you can effect the behavior of a Method by changing the value in a variable though). – Tim B Dec 17 '13 at 14:34
1

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

Anirban Nag 'tintinmj'
  • 5,572
  • 6
  • 39
  • 59