Java Frame Closing Button

Java Frame Closing Button

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 a 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 component Button. The component may be any one like a checkbox etc.

Using a Component (Java Frame Closing Button)

We have seen earlier how to close the window using WindowListener and WindowAdapter. The same can be done using any GUI component like a button or checkbox etc. In the following program, a button is used.

Java Frame Closing Button

import java.awt.*;
import java.awt.event.*;

It is a must to import two packages for every AWT program with event-handling – java.awt and java.awt.event. In the above code, java.awt package is required for Frame and Button classes and java.awt.event package is for ActionEvent and ActionListener.

The program, FrameClosing4(), implements ActionListener. We know ActionListener handles the events of a button. The button btn is registered with ActionListener with the method addActionListener(this). The parameter this represents an object of ActionListener (or to say, an object of FrameClosing4 that implements ActionListener). The event handling of button is discussed elaborately in event handling mechanism.

Leave a Reply

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