Java Swing BorderLayout Example

In this example, we will learn how to use BorderLayout in GUI/swing based applications.
BorderLayout is a simple layout manager that can be handy in certain layouts. It is a default layout manager for JFrame, JWindow, JDialog, JInternalFrame, and JApplet.

Java Swing BorderLayout Example

The following example demonstrates the usage of a BorderLayout manager. Note that in the below example, a BorderLayout object has five areas. These areas are specified by the BorderLayout constants:
Here is the complete code:
package net.javaguides.javaswing.examples;

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;

 * Class demonstrates the usage of BorderLayout.
 * @author
public class BorderLayoutDemo {
    public static boolean RIGHT_TO_LEFT = false;

    public static void addComponentsToPane(Container pane) {

        // set BorderLayout to Panel
        pane.setLayout(new BorderLayout());

        if (!(pane.getLayout() instanceof BorderLayout)) {
            pane.add(new JLabel("Container doesn't use BorderLayout!"));

        if (RIGHT_TO_LEFT) {

        JButton button = new JButton("Button 1 (PAGE_START)");
        pane.add(button, BorderLayout.PAGE_START);

        //Make the center component big, since that's the
        //typical usage of BorderLayout.
        button = new JButton("Button 2 (CENTER)");
        button.setPreferredSize(new Dimension(200, 100));
        pane.add(button, BorderLayout.CENTER);

        button = new JButton("Button 3 (LINE_START)");
        pane.add(button, BorderLayout.LINE_START);

        button = new JButton("Long-Named Button 4 (PAGE_END)");
        pane.add(button, BorderLayout.PAGE_END);

        button = new JButton("5 (LINE_END)");
        pane.add(button, BorderLayout.LINE_END);

     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
    private static void createAndShowGUI() {

        //Create and set up the window.
        JFrame frame = new JFrame("BorderLayoutDemo");


        //Set up the content pane.

        //Display the window.

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {


Related Swing Examples

  • Java Swing Exit Button - In this post, I show you how to exit a Swing application when clicking on the exit button.
  • Java Swing Combo Box Example - In this post, I show you how to create a combo box using a JComboBox component in swing-based applications.
  • Java Swing Slider Example - In this post, I show you how to create a slider using the JSlider component in swing-based applications.