Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanup before exiting Java application

Tags:

java

swing

nio

I'm writing a small Java application using Swing. The application also has a networking component.

I want to run some code before exiting(close channels, keys, etc).Is there a way to do this, without adding an Exit button in my interface, in which to do my cleanup, then do System.exit()?

like image 874
adivasile Avatar asked Apr 17 '11 19:04

adivasile


2 Answers

You can use the Runtime#addShutdownHook function to add a function to run when the JVM shuts down.

like image 198
T.J. Crowder Avatar answered Sep 27 '22 23:09

T.J. Crowder


You should be able to do what you want in windowClosing(), shown here.

like image 29
trashgod Avatar answered Sep 27 '22 23:09

trashgod