BorderLayout Layout Manager

Usage of BorderLayout

BorderLayout layout manager can place GUI components in frame at five possible positions. It actually put components in frame along with one of frame's border.

These position are

  1. BorderLayout.PAGE_START
  2. BorderLayout.PAGE_END
  3. BorderLayout.LINE_START
  4. BorderLayout.LINE_END
  5. BorderLayout.CENTER
Note BorderLayout is default layout for a JFrame. While using BorderLayout if no position is specified for adding component, that component will be placed on CENTER position by default.

Program

/* 
   Use of BorderLayout 
   www.jgyan.com
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class borderlayout
 {
  public static void main(String arg[])
   {
    JFrame jf=new JFrame("BorderLayout");
    jf.setSize(400,400);
	
	// Creating Button 
	JButton b1=new JButton("TOP");
	JButton b2=new JButton("DOWN");
	JButton b3=new JButton("LEFT");
	JButton b4=new JButton("RIGHT");
	JButton b5=new JButton("CENTER");
    
	// Add buttons on different locations
	
	jf.add(b1,BorderLayout.PAGE_START);
	jf.add(b2,BorderLayout.PAGE_END);
	jf.add(b3,BorderLayout.LINE_START);
	jf.add(b4,BorderLayout.LINE_END);
	jf.add(b5,BorderLayout.CENTER);
	
	jf.setVisible(true);
	jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
 
 }


Execution

C:/jgyan/Desktop> javac borderlayout.java
C:/jgyan/Desktop> java borderlayout

Output

Explanation

BorderLayout is default layout manager for JFrame that's why there is no need to set layout for frame as BorderLayout. In order to add a GUI component on one of five position, position has to be specified while adding that component in frame.

Following code actually add button b1 at PAGE_START position, which is along the top border. Button b2 is added along with bottom border and so on.

jf.add(b1,BorderLayout.PAGE_START);
jf.add(b2,BorderLayout.PAGE_END);
jf.add(b3,BorderLayout.LINE_START);
jf.add(b4,BorderLayout.LINE_END);
jf.add(b5,BorderLayout.CENTER);