Java: BorderLayout

java.awt.BorderLayout divides a container (eg, JPanel) into 5 geographical sections: North, South, East, West, and Center.

Resizing

The window on the left was created by the sample code below. This same window was made larger by dragging on the lower right corner. Note which components had horizontal space added to them and which had vertical space added to them.

To prevent component resizing, put a component into a Panel with a FlowLayout, and then put that panel in the BorderLayout. This is a common way to prevent resizing. The enclosing FlowLayout panel will stretch, but the component in it will not.

Not all regions are required

If nothing has been added to a region, the neighboring regions will expand to fill that space.

This window was created with 5 pixel gaps using only the NORTH, WEST, and CENTER regions. It was then resized, which added both vertical and horizontal space to the center, and each of the others was expanded as needed.

Constructors

If you don't need any space between regions, use the default constructor. You can also specify the number of pixels between regions.

p.setLayout(new BorderLayout());  // default is no gaps
p.setLayout(new BorderLayout(hgap, vgap);

Where hgap and vgap are the distances in pixels between the regions.

Example

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
// layouts/borderLayout/BorderTest.java - Demo use of BorderLayout
// Fred Swartz - 2004-11-03 (after Bush was elected).

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

///////////////////////////////////////////////// class BorderTest
class BorderTest {
    //================================================ method main
    public static void main(String[] args) {
        JFrame window = new BorderTestGUI();
        window.setTitle("BorderTest");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}

////////////////////////////////////////////// class BorderTestGUI
class BorderTestGUI extends JFrame {
    BorderTestGUI() {
        //... Create components (but without listeners)
        JButton north  = new JButton("North");
        JButton east   = new JButton("East");
        JButton south  = new JButton("South");
        JButton west   = new JButton("West");
        JButton center = new JButton("Center");
        
        //... Get content pane, set layout, add components
        Container content = this.getContentPane();
        content.setLayout(new BorderLayout());
        
        content.add(north , BorderLayout.NORTH);
        content.add(east  , BorderLayout.EAST);
        content.add(south , BorderLayout.SOUTH);
        content.add(west  , BorderLayout.WEST);
        content.add(center, BorderLayout.CENTER);
        this.pack();
    }
}