Layout Managers in AWT-


Layout Managers (java.awt.LayoutManager interface) -

Layout Managers are used to arrange different components (Button, Label, TextField etc) within different types of windows (Panel, Applet, Frame etc.).
They control the size and position of components within container.
Each Container object has a associated LayoutManager. A layout manager is an object of any class that implements LayoutManager interface.

Setting Layout -

We can set the layout of any container by setLayout() method. It has the following syntax -
public void setLayout(LayoutManager obj)  
Where obj is the object of desired layout manager


AWT provides the following layout manager classes -
  • java.awt.FlowLayout
  • java.awt.BorderLayout
  • java.awt.GridLayout
  • java.awt.GridBagLayout
  • java.awt.CardLayout

1- FlowLayout -

It is the default layout for Panel and Applet. In FlowLayout components are placed one after another in a line in left to right or top to bottom direction, once the line are filled component will be placed in the next line just like text in any text editor.
There will be a small gap between components paced within container by default; this gap can also be specified by user.
FlowLayout defies the following constructors -
public FlowLayout()
It creates a layout where components will be centrally aligned, and there will be a gap of 5 pixels between 
each components.         
public FlowLayout(int alignment)
It creates a layout with the specified alignment, and there will be a gap of 5 pixels between each components.
Alignment can have one of the following values -  
FlowLayout.CENTRE
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING   
public FlowLayout(int alignment, int horz_gap, int vert_gap)
It creates a layout with specified alignment and horizontal and vertical gab between components.         

Example -

In this example we are adding various buttons to Frame, which has FlowLayout. So once first line will be filled by Button (components) , then Button (components) will be placed in next line and so on.


import java.awt.*;
import java.awt.event.*;
public class Test
{
    public static void main(String args[])
    {
        Frame fr = new Frame("FlowLayout Demo");
        fr.setSize(300, 300);
        fr.setVisible(true);
        FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
        // create a FlowLayout with Left alignment
        fr.setLayout(fl);
        // set FlowLayout to Frame
        Button b1 = new Button("10");
        Button b2 = new Button("20");
        Button b3 = new Button("30");
        Button b4 = new Button("40");
        Button b5 = new Button("50");
        Button b6 = new Button("60");
        Button b7 = new Button("70");
        Button b8 = new Button("80");
        Button b9 = new Button("90");
        Button b10 = new Button("100");
        
        fr.add(b1);
        fr.add(b2);
        fr.add(b3);
        fr.add(b4);
        fr.add(b5);
        fr.add(b6);
        fr.add(b7);
        fr.add(b8);
        fr.add(b9);
        fr.add(b10);
        fr.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }

        });
    }
}
        

2- BorderLayout -

It is the default layout for Frame window. In this entire Container area is partitioned in five regions ? centre, north, south, east and west. One region can contain only one component within it, so a maximum of five components can be added in it.
If we required to add more than one component in a region, we can do so by adding those components in any other Container and finally add that Container in that region of Border layout.
BorderLayout use the following integer constant to specify regions -
  • public static final int CENTRE
  • public static final int NORTH
  • public static final int SOUTH
  • public static final int EAST
  • public static final int WEST

BorderLayout defies the following constructors -
public BorderLayout()
It creates a default border layout with no gap between the components.
public BorderLayout(int horz_gap, int vert_gap)
It create a layout with the specified horizontal and vertical gap between the components.

Example -

In this example we are adding 5 buttons, one button in each region.


import java.awt.*;
import java.awt.event.*;
public class Test
{
    public static void main(String args[])
    {
        Frame fr = new Frame("BorderLayout Demo");
        fr.setSize(400, 400);
        fr.setVisible(true);
        BorderLayout bl = new BorderLayout();
        // create a BorderLayout with no gap between the components
        fr.setLayout(bl);
        // set BorderLayout to Frame
        Button b1 = new Button("CENTRE BTN");
        Button b2 = new Button("NORTH BTN");
        Button b3 = new Button("SOUTH BTN");
        Button b4 = new Button("EAST BTN");
        Button b5 = new Button("WEST BTN");
    
        fr.add(b1, BorderLayout.CENTER);
        fr.add(b2, BorderLayout.NORTH);
        fr.add(b3, BorderLayout.SOUTH);
        fr.add(b4, BorderLayout.EAST);
        fr.add(b5, BorderLayout.WEST);
        
        fr.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }

        });
    }
}
        

Using Insets in layouts -

java.awt.Insets class object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title.
It has the following constructor -
public Insets(int top, int left, int bottom, int right)
The values top, left, bottom and right specify the space between Container and its enclosing window.
To specify this space you need to override getInsets() method provided by java.awt.Container class. It has the following general form -
public Insets getInsets()
It returns an object of Insets that define the desired space between Container and its enclosing window.

Example -

Here we are using the same example used in Border layout with 20 pixels of space from all side.


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class EventDemo2 extends Applet
{
    public void init()
    {

        BorderLayout bl = new BorderLayout();
        // create a BorderLayout with no gap between the components
        setLayout(bl);
        // set BorderLayout to Frame
        Button b1 = new Button("CENTRE BTN");
        Button b2 = new Button("NORTH BTN");
        Button b3 = new Button("SOUTH BTN");
        Button b4 = new Button("EAST BTN");
        Button b5 = new Button("WEST BTN");

        add(b1, BorderLayout.CENTER);
        add(b2, BorderLayout.NORTH);
        add(b3, BorderLayout.SOUTH);
        add(b4, BorderLayout.EAST);
        add(b5, BorderLayout.WEST);

        }

        public Insets getInsets()
        {
			Insets ist = new Insets(20, 20, 20, 20);
            return ist;
        }
}
        

3- GridLayout -

GridLayout placed components in two dimensional rectangular grid. Where number of rows and columns specify the total components the container can have.
It partitioned the container area into equal size rectangular boxes, where each rectangular box can contain one component.
It has the following constructors -
public GridLayout()
It create a layout with one column per component , in a single row.    
public GridLayout(int rows, int columns)
It creates layout with the specified number of rows and columns. All components in the layout are given equal size. 
And there will be no space between components.    
public GridLayout(int rows, int columns, int horz_gap, int vert_gap)
It creates layout with the specified number of rows and columns, and specified horizontal and vertical gap 
between components. All components in the layout are given equal size. 

Example -



import java.awt.*;
import java.awt.event.*;
public class Test 
{
    public static void main(String args[])
    {
        Frame fr = new Frame("GridLayout Demo");
        fr.setSize(400, 400);
        fr.setVisible(true);
        GridLayout gl = new GridLayout(3, 3);
        fr.setLayout(gl);
        Button b1=new Button("1");  
        Button b2=new Button("2");  
        Button b3=new Button("3");  
        Button b4=new Button("4");  
        Button b5=new Button("5");  
        Button b6=new Button("6");  
        Button b7=new Button("7");  
        Button b8=new Button("8");  
        Button b9=new Button("9");  
          
    fr.add(b1);fr.add(b2);fr.add(b3);fr.add(b4);fr.add(b5);  
    fr.add(b6);fr.add(b7);fr.add(b8);fr.add(b9);  

    fr.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }

    });
    }
   
}    

4- CardLayout -

CardLayout uses the concept of card deck, It treats each component in the container as a card and container can have a deck of such cards and only one card can be visible at a time in the container.
This layout can be useful where components need to be hidden and visible depending upon user needs.
CardLayout can store several different layouts. To use the CardLayout you need to follow the following steps -
1- Create a container and set its layout to CardLayout. This container will act as a deck.
2- Create other containers with different layouts as needed. These containers will act as cards of deck.
3- Finally add these cards in the deck i.e. add these containers in the container that has CardLayout.
In the deck only one card can be visible at a time and you can also switch from one card to another.
CardLayout provides the following methods to activate a card in the deck -
1- public void first(Container deck) - It activates the first card of the deck.
2- public void next(Container deck)- It activates next card of the deck. If the current visible card is the last one then it will activates the first card.
3- public void previous(Container deck) - It activates previous card of the deck. If current visible card is the first one then it will activates the last card of the deck.
4- public void last(Container deck) - It activates the last card of the deck.
5- public void show(Container deck, String name) - It display the card whose name is passed in name parameter.

CardLayout provides the following constructors -
public CardLayout() 
Creates a default card layout.
public Cardlayout(int horz_gap, int vert_gap) 
creates a card layout with the specified horizontal and vertical gap between components.

To add cards in deck you need to use a new version of add() method -
public void add(Component card_obj, Object Name)
Here name is a string that specifies the name of the card whose object is specified by will be the name of card 
whose object card_obj.

Example -

In this example there will be 3 panels, first panel have the CardLayout will be act as a deck, second panel have Grid Layout will act as first card of deck, 3rd panel have default FlowLayout will act as second card of deck. First card have a list of animals and second card have a list of fruits. When user clicks on Animal button, it will display first card and if user click on fruits button second card will be displayed.


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventDemo2 extends Applet implements ActionListener
{
    Button b1, b2;
    Panel deck;
    CardLayout cl;
    public void init()
    {
        b1 = new Button("Animals");
        b2 = new Button("Fruits");
        add(b1);
        add(b2);

// create main container (deck) with layout set to CardLayout
        deck = new Panel();   
        cl = new CardLayout();
        deck.setLayout(cl);

//Create first card of deck with Grid Layout
        Panel card1 = new Panel();
        GridLayout gl = new GridLayout(2, 2);
        card1.setLayout(gl);
        Label l1 = new Label("Lion");
        Label l2 = new Label("Zebra");
        Label l3 = new Label("Tiger");
        Label l4 = new Label("Cow");
        card1.add(l1);
        card1.add(l2);
        card1.add(l3);
        card1.add(l4);

//Create second card with default FlowLayout
        Panel card2 = new Panel();
        Label l5 = new Label("Mango");
        Label l6 = new Label("Orange");
        Label l7 = new Label("Banana");
        card2.add(l5);
        card2.add(l6);
        card2.add(l7);

// add cards to deck
        deck.add(card1, "Animals");
        deck.add(card2, "Fruits");

// finally add deck to main window i.e. Applet in this case
        add(deck);

        b1.addActionListener(this);
        b2.addActionListener(this);

    }
   public void actionPerformed(ActionEvent e)
   {

// If click on b1 button, it will show card1 contents
       if(e.getSource() == b1)
       {
           cl.show(deck, "Animals");
       }

// If click on b2 button, it will show card2 contents

       else
       {
           cl.show(deck, "Fruits");
       }
   }
} 
        

GridBagLayout -

GridBagLayout gives you more control over how to arrange components in your container. Here you can align components vertically, horizontally or along the baseline depending on your needs. The key benefits of GridBagLayout are that here components can be of different sizes and each row in the grid can have different numbers of columns. This is why the layout is called grid bag layout as it is a collection of small grids joined together. Each component managed by GridBagLayout is associated with an object of GridBagConstraints class. GridBagConstraints object determines the size and location of each component in grid bag.
To use the GridBagLayout you have to follows the following steps -
1 - Create a GridBagLayout object and assign it to container.
2 - Create components you want to add to grid bag and set constrains for each components.
3 - Finally add the components to the container that has GridBagLayout.

GridBagLayout defines the following constructor -
public GridBagLayout()
It creates default grid bag layout.

continue............................