Closing AWT Frame and Terminating Application

This section provides solutions and sample program on how to close an AWT frame and terminate the application.

Problem: I have a frame window displayed on the screen and I want to close the frame and terminate the application, when user invokes the close command from the window's system menu, or clicks on the close icon from the window's system icon list.

Solution: You can create a new window event listener class and add an object of this listener class to the Frame object. In the new window event listener, you can implement your owner version of windowClosing() handler method. Of course, the quickest way to create a new window event listener class is to extend the WindowAdapter class.

The following sample code, FrameClose.java, shows you how to do this.

/* FrameClose.java
 * Copyright (c) 1997-2024 HerongYang.com. All Rights Reserved.
 */
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameClose  {
   public static void main(String[] a) {
      Frame f = new Frame();
      f.setTitle("Closing Frame with Window Listener");
      f.setBounds(100,50,500,300);
      f.addWindowListener(new MyWindowListener());
      f.setVisible(true);
   }
   static class MyWindowListener extends WindowAdapter {
      public void windowClosing(WindowEvent e) {
         System.exit(0);
      }
   }
}

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

AWT (Abstract Windows Toolkit)

 What Is AWT (Abstract Windows Toolkit)

 HelloAWT.java - My First AWT Program

Closing AWT Frame and Terminating Application

 Drawing Graphics - Using paint() on Frame or Component

 Creating Labels with java.awt.Label Class

 Creating Buttons with java.awt.Button Class

 AWT Button Action Handler at the Component Level

 AWT Button Action Handler at the Frame Level

 AWT Button Mouse Click Handler at the Frame Level

 AWT TextField and ActionListener

 MenuBarTest.java - AWT Menu Bar Test Program

 MenuTest.java - AWT Menu Test Program

 MenuItemTest.java - AWT Menu Item Test Program

 MenuItemActionListenerTest.java - AWT Menu Item Action Listener

 Integration with Desktop System

 Archived Tutorials

 References

 Full Version in PDF/EPUB