Reputation: 619
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
Reputation: 5762
Add a WindowListner
to your JFrame
and override windowClosing
method and do a pop-up with JOptionPane warning user.
Upvotes: 1
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
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