Advanced Java Programming - Old Questions

8. Discuss border layout with suitable example.

5 marks | Asked in 2070

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.

Components of the BorderLayout Manager

·         BorderLayout.NORTH

·         BorderLayout.SOUTH

·         BorderLayout..EAST

·         BorderLayout.WEST

·         BorderLayout.CENTER

BorderLayout Constructors:

BorderLayout()

creates a border layout but with no gaps between the components.

BorderLayout(int hgap, int vgap)

creates a border layout with the given horizontal and vertical gaps between the components.


Example:

import java.awt.BorderLayout;  

import javax.swing.JButton;

import javax.swing.JFrame;

  

public class BorderLayoutExample {  

BorderLayoutExample(){  

    JFrame f=new JFrame();  

      

    JButton b1=new JButton("NORTH");;  

    JButton b2=new JButton("SOUTH");;  

    JButton b3=new JButton("EAST");;  

    JButton b4=new JButton("WEST");;  

    JButton b5=new JButton("CENTER");;  

      

    f.add(b1,BorderLayout.NORTH);  

    f.add(b2,BorderLayout.SOUTH);  

    f.add(b3,BorderLayout.EAST);  

    f.add(b4,BorderLayout.WEST);  

    f.add(b5,BorderLayout.CENTER);  

      

    f.setSize(300,300);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new BorderLayoutExample();  

}  

}