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?
Asked
Active
Viewed 172 times
3 Answers
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
-
Sorry but could you tell me what @override mean? I've never used that character @ in **Java** – user3102872 Dec 17 '13 at 13:51
-
@user3102872: You will get detailed answer in this link http://stackoverflow.com/a/94411/814074 – Sachin Dec 19 '13 at 08:14
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
-
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