File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes catching the event before a java program will end . . . Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "catching the event before a java program will end . . ." Watch "catching the event before a java program will end . . ." New topic

catching the event before a java program will end . . .

Sanjeev Charla
Ranch Hand

Joined: Apr 02, 2009
Posts: 90

i am not in a gui program to do something before window is closing . . . show me, how to catch the sudden cancellation of a java program.

but how to know before, when a jvm is exiting normally??
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
not sure I'm reading this right, but one of the ways is to set the frame's closeOperation to DO_NOTHING_ON_CLOSE,
then add your own windowListener, and in windowClosing do what you want before calling System.exit(..)
Peter Taucher
Ranch Hand

Joined: Nov 18, 2006
Posts: 174
A window listener would react on behalf of the window. Some applications don't necessarily run in window mode. A shutdown hook would always be possible (depends on your targets/presets):

Censorship is the younger of two shameful sisters, the older one bears the name inquisition.
-- Johann Nepomuk Nestroy
Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

Shutdown hooks are indeed the way to go. They will only not be called if the JVM is terminated forcefully (e.g. using Runtime.getRuntime().halt(), or by killing the process from the operating system)

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
This is probably a more helpful link about shutdown hooks; note it is a bit old however. Another (also old) link.

Shutdown hooks are nice things
I agree. Here's the link:
subject: catching the event before a java program will end . . .
It's not a secret anymore!