Credits

Saturday, March 6, 2010

Java's Border Layout

A Layout Manager arranges the sizes, location and arrangement of components inside a container. There are six different layouts that can be used. In this post, one useful layout is the border layout. Use this layout if you need five regions of your container: EAST, WEST, NORTH, SOUTH,  and CENTER.


Should only few regions are used, the unused regions shrunk to give space to the used portions. See sample program below to display a container with buttons on the set regions.

[+/-] show/hide



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

public class BorderLayoutDemo extends JFrame{
JButton bN,bS, bE, bW;
Container con = getContentPane();

public BorderLayoutDemo()
{
bN=new JButton("North");
bS=new JButton("Center");
bE=new JButton("East");
bW=new JButton("West");

con.setLayout(new BorderLayout());

con.add(bN,BorderLayout.NORTH);
con.add(bS,BorderLayout.CENTER);
con.add(bE,BorderLayout.EAST);
con.add(bW,BorderLayout.WEST);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main (String [] args){
BorderLayoutDemo frm = new BorderLayoutDemo();
frm.setSize(400,300);
frm.setTitle("Border Layout Demo");
frm.setVisible(true);
}
}

AddThis