Java Documentation

BorderLayout: Five-Region Layout

BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST, and CENTER.

Example: Buttons in BorderLayout regions

This example creates five buttons and places each into a different BorderLayout region.

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

class MyFrame extends JFrame {
	MyFrame() {
		setTitle("Layouts - Borderlayout");

		BorderLayout B1 = new BorderLayout(20, 20);
		 // here 20 and 20 is horizontal and Vertical gap/space
		 /*
		BorderLayout(int hgap, int vgap);
		 */
		setLayout(B1);		

		JButton b1 = new JButton("Button 01");
		JButton b2 = new JButton("Button 02");
		JButton b3 = new JButton("Button 03");
		JButton b4 = new JButton("Button 04");
		JButton b5 = new JButton("Button 05");

		add(b1, BorderLayout.EAST);
		add(b2, BorderLayout.WEST);
		add(b3, BorderLayout.NORTH);
		add(b4, BorderLayout.SOUTH);
		add(b5, BorderLayout.CENTER);

		setVisible(true);
		setSize(500, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

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

What is BorderLayout?

BorderLayout is the default layout for JFrame's content pane. It has five regions and is useful for building typical application windows.

  • Regions: NORTH, SOUTH, EAST, WEST, CENTER.
  • Only one component per region is allowed.
  • Gaps between regions can be controlled with hgap and vgap.

Line-by-line: Understanding the BorderLayout code

We focus on how the layout and regions are configured.

BorderLayout B1 = new BorderLayout(20, 20);
setLayout(B1);

Creates a BorderLayout with 20-pixel gaps horizontally and vertically between regions, then applies it to the frame.

add(b1, BorderLayout.EAST); ... add(b5, BorderLayout.CENTER);

Adds each button to a specific region so you can visually see where each area is located.

When to use BorderLayout

Use BorderLayout for typical application windows: toolbars at the top, status bar at the bottom, navigation on the left, and main content in the center.