Java run code before exit of the application

If you want to run a section of code immediately before your application exits then this article will tell you how to do it. We will be using the WindowClosing event of the main JFrame class of your application.

In the Deign View of your application in the project component navigator right click the JFrame and go to Events->Window->WindowClosing

Add the code you want to execute. I have just added a demo code displaying a message box.The application will exit automatically after this code is executed.

private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
   JOptionPane.showMessageDialog(null, "I am displayed before window will be closed ! ");

That is all.

If you liked this article please do leave a reply and share it with friends.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.