Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
updateZonas();
db.close();
}
});
This works for any Java application(Swing/AWT/Console)
Answer from Santhosh Kumar Tekuri on Stack OverflowRuntime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
updateZonas();
db.close();
}
});
This works for any Java application(Swing/AWT/Console)
Are you using a JFrame? if so you can try this:
myframe.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(WindowEvent winEvt) {
updateZonas();
db.close();
System.exit(0);
}
});
The Runtime.addShutdownHook method can be used to add a shutdown hook, which is basically a unstarted Thread, which executes on shutdown of the Java Virtual Machine.
However, this is territory that should to be tread carefully, as it is being performed at a very sensitive time of the JVM's life cycle. From the API Specifications for the Runtime.addShutdownHook method:
Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible.
In any event, be sure to read up a bit on how shutdown hooks work, as they probably should not be approached without some good preparation. Be sure to carefully read the API Specification for the Runtime.addShutdownHook method.
Here's are a couple articles I found from searching for information for this answer:
Shutdown Hooks -- it shows a little example of how a shutdown hook is added for logging at shutdown.
Design of the Shutdown Hooks API -- addresses some design decisions of shutdown hooks in a question and answer style.
The function Runtime.addShutdownHook(Thread thehook) allows you to register a hook into the Java Virtual Machine.
The hook works as an initialized but unstarted thread, which will be called by the JVM on exit. In case you register more than one hook, note that the order in which the hooks are called is undefined.