Action before window closes using JFrame close button

You might be wondering with the questions like How to override windowsClosing event in JFrame or do something before window closes after user presses x button or how to control the action of closing the JFrame. Lets see the the solution to the problem you might be facing.

So in order to add the our own event implementation on closing action or when user press "X" on JFrame, we need to use method setDefaultCloseOperation and we need to use WindowAdapter class.

WindowAdapter is an abstract adapter class for receiving window events.We are using WindowAdapter class for creating listener object. WindowAdapter class provides lot of methods such as windowActivated, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowGainedFocus, windowIconified, windowLostFocus, windowOpened, windowStateChanged etc. We can override these methods which are of our interest.

So for our interest when we create the listener object we can use windowClosing method which takes WindowsEvent as argument. windowClosing method is invoked when a window is in the process of being closed. At this point we can override this method to write our own implementation for doing the things we want before user close or press "X" button on JFrame.

In following code as we can see we have used setDefaultCloseOperation method to which we are setting option as do nothing on close using the JFrame constant JFrame.DO_NOTHING_ON_CLOSE.
Then we are creating WindowAdapter object and overriding windowClosing method in which you can add the changes you want to do before actual closing happens. And then we need to add this listener object to the JFrame using addWindowListener method as shown in code below.

Example for setting own action before close action of JFrame.

JFrame framCloseAction = new JFrame();

framCloseAction.addWindowListener( new WindowAdapter()
   public void windowClosing(WindowEvent e)
      // Here you can write your own implementation which you want to //do before closing.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


  1. how can i go next window using main page i have two buttons "home" and "next", by clicking on "next" button, home page will disappear and appear next new window in that place.
    please help me...

  2. Hello Narendar,

    You can call remove or removeAll as per your requirement on action event and then add your new component, Then you need to call validate and repaint , you can check article about repaint and validate here