Academic Java    Java Tutorial  >  Swing  >  BorderLayout

BorderLayout Example

Java BorderLayout EXAMPLE output The layout manager BorderLayout, which is the default layout manager for a JFrame's content pane, divides a container into five regions, each of which takes one component that isn't usually displayed with its preferred size, as you will see.

You will need to experiment with the displayed frame by dragging its sides or corners. Observe how the component in the CENTER region takes as much space as possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// BorderLayout Example
import java.awt.*;
import javax.swing.*;

class BorderLayoutExample {

   public static void main(String[] args) {

      JFrame frame = new JFrame();
      Container cp = frame.getContentPane();

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

      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

10 Note that a layout manager is not explicitly assigned to the frame's content pane here.BorderLayout is its default layout manager and is automatically assigned to it here.

12-16 The add() method can take two parameters, the component to be added and its BorderLayout region expressed as a class field.

* BorderLayout Examples