Frames and Windows
Site Admin
· 11 Sep 2026
· 1 views
Creating a Frame
A Frame is a top-level window with a title bar and resize borders. Subclass it and add components in the constructor:
import java.awt.*;
public class FrameTest extends Frame {
FrameTest() {
setTitle("My Window");
setSize(400, 250);
setLayout(new FlowLayout());
add(new Button("OK"));
add(new Button("Cancel"));
setVisible(true);
}
public static void main(String[] args) {
new FrameTest();
}
}
Closing the Window Properly
By default clicking the close button does nothing. Implement WindowAdapter:
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Key Points
- Extend Frame (or use a Frame object) for a top-level window.
- Always call setVisible(true) after setting size and components.
- Add a WindowListener so the window can actually close.