19

How to get to the application closing event?

I want to get application to save all unsaved operations or show the user a message "Are you sure about closing without saving all data?" something like this.

If this will be helpful - the application is a SingleFrameAplication using Swing.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Bulit
  • 975
  • 6
  • 15
  • 26

3 Answers3

31

You could use a shutdown hook. It works for Swing, AWT and even console applications.

Example:

Runtime.getRuntime().addShutdownHook(new Thread()
{
    @Override
    public void run()
    {
        //do your stuff
    }
});
c0dehunter
  • 6,412
  • 16
  • 77
  • 139
  • 5
    be cautious using roseindia links. please read http://balusc.blogspot.com/2008/06/what-is-it-with-roseindia.html I would reccomend http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread) as a link instead – Sean Feb 16 '12 at 20:02
  • 1
    @Sean, thanks for the warning! I have edited the answer with a more legitimate link. – c0dehunter Feb 16 '12 at 20:16
3

You have to add WindowListener to your JFrame / JDialog, about closing event is there method public void windowClosing(WindowEvent e) { code example here

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

You can use sun.misc.Signal or Runtime.getRuntime().addShutdownHook

More info

Anton
  • 5,831
  • 3
  • 35
  • 45