You can either add a listener to whatever event closes the application. You can use a WindowListener to detect when people click the X. Tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html
Or you can look into shutdown hooks.