How do I arrange components using BorderLayout in Java Swing?

Use BorderLayout to arrange components around a central area. It works well for a window with a header at the top, a status bar at the bottom, and content in the middle.

In this example, you will place a button in each of the five regions and see how they resize with the window.

Source code

Save the following code as BorderLayoutExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BorderLayoutExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JPanel panel = new JPanel(new BorderLayout(8, 8));
        panel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));

        panel.add(new JButton("North"), BorderLayout.NORTH);
        panel.add(new JButton("South"), BorderLayout.SOUTH);
        panel.add(new JButton("West"), BorderLayout.WEST);
        panel.add(new JButton("East"), BorderLayout.EAST);
        panel.add(new JButton("Center"), BorderLayout.CENTER);

        JFrame frame = new JFrame("BorderLayout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.setSize(480, 260);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the five BorderLayout regions, with North and South spanning the width and Center between West and East

Explanation

new BorderLayout(8, 8) sets an 8-pixel horizontal gap and an 8-pixel vertical gap between neighboring components. The empty border adds 12 pixels of padding around the panel.

The second argument to panel.add() selects the region:

panel.add(new JButton("Center"), BorderLayout.CENTER);

Each region uses the available space differently:

Region How it behaves when the window grows
NORTH and SOUTH Stretch horizontally and keep their preferred height
WEST and EAST Stretch vertically between the top and bottom regions and keep their preferred width
CENTER Fills the space left over in both directions

Each region holds one component. To place several controls in the same region, put them in a JPanel and add that panel to the region. For example, a header panel might contain a title and several buttons.

Run the example

javac BorderLayoutExample.java
java BorderLayoutExample

Drag the right edge of the window outward. The North, Center, and South buttons grow wider, while West and East keep their widths. Then drag the bottom edge downward: West, Center, and East grow taller.

How do I display a message dialog in Java Swing?

Use JOptionPane.showMessageDialog() to display a short message with an OK button. This example opens an information dialog without creating a separate JFrame.

Source code

Save the following code as MessageDialogExample.java:

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class MessageDialogExample {
    void main() {
        SwingUtilities.invokeLater(this::showMessage);
    }

    private void showMessage() {
        JOptionPane.showMessageDialog(
                null,
                "Hello from Swing!",
                "Message",
                JOptionPane.INFORMATION_MESSAGE);
    }
}

What the dialog looks like

Illustration of a dialog titled Message, with the text Hello from Swing! and an OK button

The icon and window styling depend on your system and Swing look and feel.

Explanation

The showMessageDialog() call uses four arguments:

Argument Purpose
null Shows the dialog without positioning it relative to an existing component
"Hello from Swing!" Sets the message shown inside the dialog
"Message" Sets the title shown in the title bar
JOptionPane.INFORMATION_MESSAGE Selects the information message type, which usually displays an information icon

If your application already has a window, pass its JFrame instead of null so Swing can position the dialog relative to that window.

SwingUtilities.invokeLater() schedules showMessage() on Swing’s event dispatch thread. The dialog is modal, so the call to showMessageDialog() returns after the user dismisses the dialog. It returns no value. If you need to ask a question and read the user’s choice, use showConfirmDialog().

Run the example

javac MessageDialogExample.java
java MessageDialogExample

A dialog titled Message displays Hello from Swing!. Click OK to dismiss it.

How do I read text from a JTextField in Java Swing?

Call getText() on a JTextField to read what the user has typed. In this example, the user enters a name and clicks Say hello or presses Enter to display a greeting.

Source code

Save the following code as TextFieldExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class TextFieldExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JTextField nameField = new JTextField(14);
        JLabel nameLabel = new JLabel("Name:");
        nameLabel.setLabelFor(nameField);

        JButton greetButton = new JButton("Say hello");
        JLabel greeting = new JLabel(
                "Enter your name.", SwingConstants.CENTER);

        greetButton.addActionListener(event ->
                updateGreeting(nameField, greeting));
        nameField.addActionListener(event ->
                updateGreeting(nameField, greeting));

        JPanel form = new JPanel();
        form.add(nameLabel);
        form.add(nameField);
        form.add(greetButton);

        JPanel content = new JPanel(new BorderLayout(0, 12));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(form, BorderLayout.PAGE_START);
        content.add(greeting, BorderLayout.CENTER);

        JFrame frame = new JFrame("Text Field Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void updateGreeting(JTextField nameField, JLabel greeting) {
        String name = nameField.getText().strip();

        if (name.isEmpty()) {
            greeting.setText("Please enter your name.");
        } else {
            greeting.setText("Hello, " + name + "!");
        }
    }
}

What the window looks like

Illustration of the Swing window showing Rosa in the text field and Hello, Rosa! below it

Explanation

new JTextField(14) creates a single-line text field. The number 14 helps Swing calculate its preferred width. The user can still type more than 14 characters.

The updateGreeting() method reads the field when the user submits the name:

String name = nameField.getText().strip();

getText() returns the current text. strip() removes whitespace from both ends of the returned string without changing what appears in the field. If the result is empty, the label asks for a name. Otherwise, it displays a greeting.

Both the button and the text field have an action listener that calls updateGreeting(). The button listener runs when the button is activated. The text field listener runs when the user presses Enter while the field has focus. Both listeners run on Swing’s event dispatch thread and can update the label directly.

Run the example

javac TextFieldExample.java
java TextFieldExample

Type Rosa and click Say hello. The label displays Hello, Rosa!. Clear the field and press Enter to see Please enter your name.

How do I handle a button click in Java Swing?

Use addActionListener() to run code when a JButton is activated. In this example, clicking a button changes the text of a label in the same window.

Source code

Save the following code as ButtonClickExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class ButtonClickExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JLabel message = new JLabel(
                "Click the button.", SwingConstants.CENTER);
        JButton button = new JButton("Click me");

        button.addActionListener(event ->
                message.setText("Button clicked!"));

        JPanel panel = new JPanel(new BorderLayout(0, 12));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));
        panel.add(message, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(button);
        panel.add(buttonPanel, BorderLayout.PAGE_END);

        JFrame frame = new JFrame("Button Click");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration showing the label before and after clicking the Swing button

Explanation

The JLabel starts with the text Click the button.. The JButton displays Click me. This line connects the button to the label:

button.addActionListener(event ->
        message.setText("Button clicked!"));

addActionListener() registers a listener that Swing calls when the button is activated. The lambda is the listener in this example. Its event parameter receives information about the action, but the example only needs to update the label, so it does not use that parameter.

When the listener runs, message.setText() changes the existing label. It works whether you click the button with a mouse or activate it with the keyboard.

SwingUtilities.invokeLater() creates the window on the event dispatch thread. Swing also runs the listener on that thread, so it can update the label directly. Keep listeners short so the window stays responsive.

Run the example

javac ButtonClickExample.java
java ButtonClickExample

The window opens with the message Click the button.. Click Click me and the label changes to Button clicked!.

How do I open a Swing window on the event dispatch thread in Java?

Use SwingUtilities.invokeLater() to create and show a Swing window on the event dispatch thread (EDT). Swing uses this thread to process events such as mouse clicks and to update the interface.

This example opens a window and prints whether the code that creates it is running on the EDT.

Source code

Save the following code as SwingEdtExample.java:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class SwingEdtExample {
    void main() {
        IO.println("main() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        IO.println("showWindow() on the EDT: "
                + SwingUtilities.isEventDispatchThread());

        JFrame frame = new JFrame("Hello, Swing!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel("Welcome to Swing", SwingConstants.CENTER));
        frame.setSize(400, 240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Hello Swing!

The window looks like the one in the previous example. The console messages show which thread runs each method.

Explanation

When you launch the program, main() runs outside the EDT. It schedules the showWindow() method with this line:

SwingUtilities.invokeLater(this::showWindow);

The method reference this::showWindow supplies the task. invokeLater() puts that task on Swing’s event queue and returns without waiting. The EDT runs the task when it reaches the front of the queue.

The showWindow() method creates the frame and label, adds the label to the frame, and makes the window visible. All of those steps run on the EDT. Calling showWindow() directly from main() would run those steps on the main thread instead.

SwingUtilities.isEventDispatchThread() checks the thread that is running the current code. It returns false in main() and true in showWindow().

Run the example

javac SwingEdtExample.java
java SwingEdtExample

The console prints:

main() on the EDT: false
showWindow() on the EDT: true

Keep work on the EDT short. A slow operation, such as downloading a file, can keep Swing from responding to clicks or repainting the window. Run slow work in the background and send interface updates back to the EDT.