BorderLayout Manager Example


BorderLayout Manager Example: After knowing the layout managers, FlowLayout and GridLayout functionality, let us go to the style of BorderLayout arrangement of components in a container. As the name indicates the container is divided into 5 regions – 4 borders (North, South, East, West) and 1 Center.

BorderLayout Manager Example

Following are the properties of BorderLayout manager.

  1. Components are added at borders and center. The position should be specified while adding the component like North or East etc.; else the default is Center.
  2. When added, say south or north, the component occupies complete width of the container and when added, say east or west, the component occupies complete height of the container. Center occupies complete remaining space.
  3. When it occupies complete width or height, another component cannot be added to the same side and if added, it is not an error, but overrides the earlier; that is, earlier goes out and the latest comes.
  4. Using BorderLayout, we can add maximum 5 components only to a container; 4 at the borders and one at the center.
  5. The default gap between the components, either horizontally or vertically, is 0 pixels which can be changed explicitly.
  6. It is the default layout manager for Frame, Dialog, FileDialog, Window and Container.
  7. It is best suitable for adding scroll bars.
Following program on BorderLayout Manager Example illustrates the addition of components to frame.
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Button;
import java.awt.Color;

public class BLDemo extends Frame
{
  public BLDemo()
  {                                    // set the layout
    setLayout(new BorderLayout());
    setBackground(Color.red);
                                       // create the components
    Button btn1 = new Button("Himalayas");
    Button btn2 = new Button("Indian Ocean");
    Button btn3 = new Button("Bay of Bengal");
    Button btn4 = new Button("Arabian Sea");
    Button btn5 = new Button("India");
              // place the components, position should be specified
    add(btn1, "North");
    add(btn2, "South");
    add(btn3, "East");
    add(btn4, "West");
    add(btn5, "Center");
                                       // frame creation methods
    setTitle("Learning BorderLayout");
    setSize(350, 300);
    setVisible(true);
  }
  public static void main(String args[])
  {                                   // just call constructor to execute the whole code
    new BLDemo();   
  }
}

BorderLayout Manager Example

Leave a Comment

Your email address will not be published.