Java Frame Closing WindowAdapter

Java Frame Closing WindowAdapter


The frame created by the programmer and displayed on the monitor comes with a title bar and three icons(buttons) on the title bar – Minimize, Maximize and Close. The first two works implicitly and the Close does not work and requires extra code to close the frame.

Java Frame Closing – 4 styles

Four styles exist to close the frame and are discussed one-by-one in this tutorial.

  1. Using WindowListener
  2. Using WindowAdapter
  3. Using Component
  4. Using Anonymous inner class

The last style is used very often as it requires less code to write. Now let us see how to close the window using the adapter.

Java Frame Closing WindowAdapter

In the following program, WindowAdapter is used instead of WindowListener to close the frame.

Java Frame Closing WindowAdapter
Using an adapter class is advantageous over a listener that allows us to override only one or two abstract methods we require and not compulsorily all the abstract methods of a listener. Adapter classes are discussed elaborately later. But the problem with adapters is they are designed as abstract classes and thereby we cannot extend to our class as the class extends already Frame (Java does not support multiple inheritance). To overcome this problem, we created one more class CloseMe and extended WindowAdapter to it.

CloseMe cm = new CloseMe();
addWindowListener(cm);

Now another problem is we have two classes CloseMe and main program FrameClosing2 which are no way related; both are separate classes. It is required to integrate or link them. An object cm of CloseMe is created and passed as parameter to addWindowListener() method. The parameter should be actually an object of WindowListener as we have done in FrameClosing1 application. But here, we are passing an object of CloseMe that extends WindowAdapter. If an object of any class that does not extend WindowAdapter is passed, the compiler raises an error.

The above two lines can replaced with one using anonymous object of CloseMe as follows.

addWindowListener(new CloseMe());

The program "Java AWT List – Multiple & Single Selection" uses this style to close the window.

Leave a Reply

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