Java Documentation

JFrame: The Main Window

JFrame is the top-level container used for most Swing desktop applications. It provides the title bar, close/minimize buttons, and the area where all other components are placed.

Example: JFrame using a separate GUI class (Method 2)

This example follows the same pattern we selected in the setup page: create a class that extends JFrame and configure the window in its constructor, while themain method simply creates an object.

JFrameDemo.java
import javax.swing.*;
import java.awt.*;

class MyFrame extends JFrame {
    MyFrame() {
        setTitle("Components - JFrame"); // sets title of the frame

        setSize(400, 400); // sets size of the frame (width, height)
        setVisible(true); // makes the frame visible on screen
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit the program when window is closed
    }
}

public class JFrameDemo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
Reference & full codeView on GitHub

What is JFrame?

In Swing, JFrame is a top-level window with a title bar and close/minimize/maximize buttons. It extends java.awt.Frame and acts as the main container for your GUI. You typically:

  • Extend JFrame in your own class (like MyFrame).
  • Configure the window inside the constructor.
  • Add panels, buttons, labels, and other components to the frame.

Line-by-line: Important JFrame methods

The following methods are used in almost every Swing program. Understand what they do before moving to more complex GUIs.

setTitle("Components - JFrame");

Sets the text shown in the title bar of the window. This is what users see at the top of the frame (e.g., on the taskbar and window caption).

setSize(400, 400);

Sets the initial size of the frame in pixels: first argument is width, second is height. Here the window will be 400×400 pixels.

setVisible(true);

Makes the frame actually appear on the screen. If you forget this call, the program runs but no window is shown.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Tells Swing what to do when the user clicks the close (✕) button. UsingEXIT_ON_CLOSEcompletely terminates the program when the frame is closed, which is ideal for simple examples.

Connecting back to our setup pattern

Notice that this example matches Method 2 from the setup page: we keep the GUI code (JFrame configuration) insideMyFrame, and let main only create an object. We will continue using this style for other components and layouts.