Layout Managers in Java: Part 1

In this article we will learn about layout managers used in Java with simple examples.

Layout Manager

A layout manager is an object that controls the size and the position of the components in the container. Every container object has a layout manager object that controls its layout.

Actually, layout managers are used to arrange the components in a specific manner. It is an interface that is implemented by all the classes of layout managers. There are some classes that represent the layout managers.

The Abstract Windowing Toolkit (AWT) has the following five layout managers:

  • java.awt.BorderLayout
  • java.awt.FlowLayout
  • java.awt.GridLayout
  • java.awt.CardLayout
  • java.awt.GridBagLayout

Some of these are used in swing:

  • javax.swing.BoxLayout
  • javax.swing.ScrollPanelLayout
  • javax.swing.GroupLayout
  • javax.swing.SpringLayout
  • and so on

In this part of article we will discuss the top three layout managers.

General rules for using layout managers

Default managers

  • For “JPanel” objects, the default layout manager is an instance of the “FlowLayout” class.
  • For “JFrame” object, the default layout manager is an instance of the “BorderLayout” class.

This layout manager is automatically consulted every time the container might need change its interface.

How to create a layout manager and associate it with a container:

  • To use the default layout manager, there is nothing to do. The constructor for each container creates a layout manager instance and initializes the container to use it.
  • To use a non-default layout manager, create an instance of the desired layout manager class and indicate the container to use it.

The following are the methods that result in calls to the container's layout manager:

  • add(), remove(), removeAll(): They add and remove Components from a Container; you can call them at any time.
  • doLayout(): It is called as the result of any paint request to a Container. It requests that the Container place and size itself and the Components it contains.
  • getPreferredSize(), getMinimumSize(), getMaximumSize(): They return the Container's original size, minimum size and maximum size, respectively. The values returned are just hints; they have no effect unless your program enforces these sizes.

Border Layout Manager

In the Border Layout Manager, the components are positioned in five different areas (regions) in other words North, South, East, West and Center. Each region may contain one component only.

If you enlarge the window, you will notice that the center area gets as much of the newly available space as possible. The other area will expand only as much as necessary to keep all the available space filled.

Example

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4.   
  5. public class Border extends JFrame  
  6.                               implements ActionListener {  
  7.    private JButton b[];  
  8.    private String names[] =  
  9.       { "Hide North Border""Hide South Border""Hide East Border",  
  10.         "Hide West Border""Hide Center Border" };  
  11.    private BorderLayout layout;  
  12.   
  13.    public Border()  
  14.    {  
  15.       super"BorderLayout" );  
  16.   
  17.       layout = new BorderLayout( 55 );  
  18.   
  19.       Container c = getContentPane();  
  20.       c.setLayout( layout );  
  21.   
  22.       // instantiate button objects  
  23.       b = new JButton[ names.length ];  
  24.   
  25.       for ( int i = 0; i < names.length; i++ ) {  
  26.          b[ i ] = new JButton( names[ i ] );  
  27.          b[ i ].addActionListener( this );  
  28.       }  
  29.   
  30.       // order is not important  
  31.       c.add( b[ 0 ], BorderLayout.NORTH );  // North position  
  32.       c.add( b[ 1 ], BorderLayout.SOUTH );  // South position  
  33.       c.add( b[ 2 ], BorderLayout.EAST );   // East position  
  34.       c.add( b[ 3 ], BorderLayout.WEST );   // West position  
  35.       c.add( b[ 4 ], BorderLayout.CENTER ); // Center position  
  36.   
  37.       setSize( 400300 );  
  38.       show();     //Show the border layout  
  39.    }  
  40.   
  41.    public void actionPerformed( ActionEvent e )  
  42.    {  
  43.       for ( int i = 0; i < b.length; i++ )  
  44.          if ( e.getSource() == b[ i ] )  
  45.             b[ i ].setVisible( false );  
  46.          else  
  47.             b[ i ].setVisible( true );  
  48.   
  49.       // re-layout the content pane  
  50.       layout.layoutContainer( getContentPane() );  
  51.    }  
  52.   
  53.    public static void main( String args[] )  
  54.    {  
  55.       Border bord = new Border();  
  56.   
  57.       bord.addWindowListener(  
  58.          new WindowAdapter() {  
  59.             public void windowClosing( WindowEvent e )  
  60.             {  
  61.                System.exit( 0 );  
  62.             }  
  63.          }  
  64.       );  
  65.    }  

Output

Border layout manager

Grid Layout Manager

Grid Layout is used to place the components in a grid of cells (rectangular). Each component takes all the available space within its cell and each cell has exactly the same size and display only one component. If the Grid Layout window is expanded, the Grid Layout changes the cell size so that the cells are as large as possible.

In other words, the layout manager divides the container into a grid so that components can be placed in rows and columns. Every component will have the same width and height, the components are added to the grid starting at the top left cell and proceeding left-to-right until the row is full, then go onto the next row, this type of layout is known as the Grid Layout Manager.

Example

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4.   
  5.   
  6. public class Grid extends JFrame implements ActionListener {  
  7.    private JButton b[];  
  8.    private String names[] = { "Contacts""Message""Call Log""Games""Settings""Applications","Music","Gallery","Organiser" };  
  9.    private boolean toggle = true;  
  10.    private Container c;  
  11.    private GridLayout grid1, grid2, grid3;  
  12.   
  13.    public Grid()  
  14.    {  
  15.       super"GridLayout" );  
  16.   
  17.       grid1 = new GridLayout( 2355);  
  18.       grid2 = new GridLayout( 32);  
  19.       grid3 = new GridLayout(35);  
  20.   
  21.       c = getContentPane();  
  22.       c.setLayout( grid3 );  
  23.   
  24.       // create and add buttons  
  25.       b = new JButton[ names.length ];  
  26.   
  27.       for (int i = 0; i < names.length; i++ ) {  
  28.          b[ i ] = new JButton( names[ i ] );  
  29.          b[ i ].addActionListener( this );  
  30.          c.add( b[ i ] );  
  31.       }  
  32.   
  33.       setSize( 400400 );  
  34.       show();  
  35.    }  
  36.   
  37.    public void actionPerformed( ActionEvent e )  
  38.    {  
  39.       if ( toggle )  
  40.          c.setLayout( grid3 );  
  41.       else if (toggle)  
  42.           c.setLayout(grid2);  
  43.       else  
  44.          c.setLayout( grid1 );  
  45.   
  46.       toggle = !toggle;  
  47.       c.validate();  
  48.    }  
  49.   
  50.    public static void main( String args[] )  
  51.    {  
  52.       Grid G = new Grid();  
  53.   
  54.       G.addWindowListener(  
  55.          new WindowAdapter() {  
  56.             public void windowClosing( WindowEvent e )  
  57.             {  
  58.                System.exit( 0 );  
  59.             }  
  60.          }  
  61.       );  
  62.    }  

Output

Grid Layout manager

Flow Layout manager

The flow layout is the most basic layout manager in which components are placed from left to right as they were added, when the horizontal row is too small to put all the components in one row then it uses multiple rows. You can align the components left, right or centre (default).

Example

  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class Flow{  
  5. JFrame f;  
  6. public Flow(){  
  7.     f=new JFrame();  
  8.   
  9.     JButton b1=new JButton("Red");  
  10.     JButton b2=new JButton("Green");  
  11.     JButton b3=new JButton("Yellow");  
  12.     JButton b4=new JButton("Purple");  
  13.     JButton b5=new JButton("Blue");  
  14.     JButton b6=new JButton("Pink");  
  15.     JButton b7=new JButton("Brown");  
  16.   
  17.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);f.add(b6);f.add(b7);  
  18.   
  19.     f.setLayout(new FlowLayout(FlowLayout.LEFT));  
  20.     //setting flow layout of right alignment  
  21.   
  22.     f.setSize(400,200);  
  23.     f.setVisible(true);  
  24. }  
  25. public static void main(String[] args) {  
  26.     new Flow();  
  27. }  

Output

Flow Layout manager

For other layout managers, please refer the link given below:
 
http://www.c-sharpcorner.com/UploadFile/9a9e6f/layout-managers-in-java-part-2/ 
 
 

Up Next
    Ebook Download
    View all
    Learn
    View all