Introduction to AWT and Applets · Introduction to Java Programming

Closing a Frame

Watch lectures

Closing a Frame

1. Problem (beginner shock!)

Click X on AWT Frame → nothing happens (window stays!). Must teach close via WindowListener (windowClosing → dispose/exit!).

2. Two Fixes (exam both! Modern + classic!)

import java.awt.*;
import java.awt.event.*;
// FIX 1: WindowAdapter (shortest! override one method!)
Frame f = new Frame("Hi");
f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        f.dispose(); // free window!
        // System.exit(0); // end program! (if main window!)
    }
});
// FIX 2: implement WindowListener (all 7 methods! verbose!)
class Closer implements WindowListener {
    public void windowClosing(WindowEvent e) { System.exit(0); }
    public void windowOpened(WindowEvent e) {}   // must stub other 6!
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
}

3. dispose() vs System.exit(0) (exam!)

dispose() = close THIS window (app lives if others open!). System.exit(0) = kill ALL (end program!).

4. Traps

  • setDefaultCloseOperation is Swing (JFrame), NOT AWT Frame (exam mixes to trap!).
  • Adapter > Listener (1 method vs 7 stubs!).

5. Exam Points

  • Adapter program + dispose vs exit — 5-7 marks, very frequent.
Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.

← All Introduction to Java Programming modules