Java Frame Close Anonymous inner class

Java Frame Close Anonymous inner class

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.

Example on Java Frame Close Anonymous inner class

In the earlier program, we used WindowAdapter class directly by creating a separate class CloseMe. Now let us further simplify the frame closing using anonymous inner class of WindowAdapter.

Java Frame Close Anonymous inner class

The method addWindowListener() is passed with an anonymous object of WindowAdapter. In the constructor of WindowAdapter, windowClosing() method is overridden. System.exit(0) closes the window.

Frame Creation Methods

Following are the three setXXX() methods that creates the frame and are required for every frame program.

1. setTitle(String name): This method gives title to the frame (window) and is displayed on the title bar. This method is optional; if not given, no title appears.
2. setSize(int width, int height): This method gives the size for the frame (window) in pixels.
3. setVisible(boolean true): This method of with true parameter makes the frame (component) visible on the monitor; else frame will be created and added to monitor but not visible.

2 thoughts on “Java Frame Close Anonymous inner class

  1. jabir ali

    thanks for your post. can we use setVisible() method instead of System.exit(0)?
    i,ve seen such usage in frame closing using inner class

Leave a Reply

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