import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class CloseWindowWithFrame { public static void main(String[] args) { // Create a Frame Frame frame = new Frame("Closing a Frame Window"); // Create a label and add it to the frame Label label = new Label("This is a Frame...", Label.CENTER); frame.add(label); // Set the size (in pixels) and location (center screen) of the frame // and make the frame visible frame.setSize(400, 400); frame.setLocationRelativeTo(null); frame.setVisible(true); // Close and destroy the window (frame) when a closing event is // detected; without this section of code, it can be difficult // for a user to end the program and make the frame go away; // note that with a JFrame (as opposed to a Frame), closing a // window can be handled with a single line of code frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } }); } }