Understanding Layout managers

Filter Course


Understanding Layout managers

Published by: Nuru

Published date: 02 Mar 2022

Understanding Layout managers

Understanding Layout managers

Layout managers refer to the manager who is used to manage all the components in a container. It helps to set fix the size and position of the AWT components. Every layout manager class implements the LayoutManager interface.

For Windows and Frames, the default LayoutManager is BorderLayout.  For Panels, the default LayoutManager is FlowLayout

Types of layout managers:

  • Flow Layout Manager,
  • Border Layout Manager,
  • Grid Layout Manager,
  • Card Layout Manager, and
  • GridBag Layout Manager

 

1. Flow Layout Manager:

The algorithm used by the FlowLayout is to lay out Components like words on a page: Left to right, top to bottom.
It fits as many Components into a given row before moving to the next row.

Example:

package Awt;

import java.awt.*;

public class FlowLayoutPrac  {
    public static void main(String [] args){
    Frame frame = new Frame();
    frame.setSize(1000, 1000);
    frame.setVisible(true);
    frame.setLayout(new FlowLayout());
    Button b1= new Button("Button A");
    frame.add(b1);
    Button b2= new Button("Button B");
    frame.add(b2);
    Button b3= new Button("Button C");
    frame.add(b3);
    Button b4= new Button("Button D");
    frame.add(b4);
    Button b5= new Button("Button E");
    frame.add(b5);

    }

}

Output:

Flow Layout Manager

2. Border Layout Manager:

The BorderLayout Manager breaks the Container up into 5 regions (North, South, East, West, and Center).  

Example:

package Awt;

import java.awt.*;

public class BorderLayout1 {
   public static void main(String[] args){
   // creating object of frame
   Frame frame = new Frame("Border Layout");
   frame.setSize(1000, 1000);
   frame.setVisible(true);
  // setting the layout as BorderLayout()
   frame.setLayout(new BorderLayout());

   // creating buttons and adding on frame separating their borders respeactively
   Button b1 = new Button("North");
   frame.add(b1, BorderLayout.NORTH);
   Button button2 = new Button("South");
   frame.add(button2,BorderLayout.SOUTH);
   Button button3 = new Button("East");
   frame.add(button3, BorderLayout.EAST);
   Button button4 = new Button("West");
   panel.add(button4, BorderLayout.WEST);
   Button button5 = new Button("Center");
   frame.add(button5, BorderLayout.CENTER);

}

}

Output:Border Layout Manager
3. Grid Layout Manager:

The GridLayout class divides the region into a grid of equally sized rows and columns. Components are added left-to-right, top-to-bottom. The number of rows and columns is specified in the constructor for the LayoutManager

Example:

package Awt;

import java.awt.*;

public class GridLayoutPrac {
        public static void main(String args[]){

        Frame frameObj= new Frame();

// creating 9 buttons
            Button btn1 = new Button("1");
            Button btn2 = new Button("2");
            Button btn3 = new Button("3");
            Button btn4 = new Button("4");
            Button btn5 = new Button("5");
            Button btn6 = new Button("6");
            Button btn7 = new Button("7");
            Button btn8 = new Button("8");
            Button btn9 = new Button("9");

/*
adding buttons to the frame since, we are using the parameterless constructor, therfore; the number of columns is equal to the number of buttons we are adding to the frame. The row count remains one.
 */
            frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
            frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
            frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);

// setting the grid layout using the parameterless constructor
            frameObj.setLayout(new GridLayout());

            frameObj.setSize(300, 300);
            frameObj.setVisible(true);
        }
    }

Output:

GridLayout

4. Card Layout Manager: 

The Java CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.

Example: Using Default Constructor

// import statements  
import java.awt.*;    
import javax.swing.*;   
import java.awt.event.*;    
  
public class CardLayoutExample1 extends JFrame implements ActionListener  
{    
  
crd;    
  
// button variables to hold the references of buttons  
JButton btn1, btn2, btn3;    
Container cPane;   
  
// constructor of the class  
CardLayoutExample1()  
{    
  
cPane = getContentPane();    
  
//default constructor used  
// therefore, components will   
// cover the whole area  
crd = new CardLayout();    
  
cPane.setLayout(crd);    
  
// creating the buttons  
btn1 = new JButton("Apple");    
btn2 = new JButton("Boy");    
btn3 = new JButton("Cat");    
  
// adding listeners to it  
btn1.addActionListener(this);    
btn2.addActionListener(this);    
btn3.addActionListener(this);    
  
cPane.add("a", btn1); // first card is the button btn1  
cPane.add("b", btn2); // first card is the button btn2  
cPane.add("c", btn3);  // first card is the button btn3  
            
}    
public void actionPerformed(ActionEvent e)   
{    
// Upon clicking the button, the next card of the container is shown  
// after the last card, again, the first card of the container is shown upon clicking  
crd.next(cPane);    
}    
  
// main method  
public static void main(String argvs[])   
{     
// creating an object of the class CardLayoutExample1  
CardLayoutExample1 crdl = new CardLayoutExample1();   
  
// size is 300 * 300          
crdl.setSize(300, 300);    
crdl.setVisible(true);    
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);    
}    
}    

Output:

cardlayout

After, this if the user clicks, it will show:

cardlayout

After, this if the user clicks, it will show:

CardLayout

After this if the user clicks, it will show the first card again and it will move in the same cycle ever and ever again.

Example: Using Parameterized Constructor

import java.awt.*;    
import java.awt.event.*;    
    
import javax.swing.*;    
    
public class CardLayoutExample2 extends JFrame implements ActionListener{    
CardLayout card;    
JButton b1,b2,b3;    
Container c;    
    CardLayoutExample2(){    
            
        c=getContentPane();    
        card=new CardLayout(40,30);    
//create CardLayout object with 40 hor space and 30 ver space    
        c.setLayout(card);    
            
        b1=new JButton("Apple");    
        b2=new JButton("Boy");    
        b3=new JButton("Cat");    
        b1.addActionListener(this);    
        b2.addActionListener(this);    
        b3.addActionListener(this);    
                
        c.add("a",b1);c.add("b",b2);c.add("c",b3);    
                            
    }    
    public void actionPerformed(ActionEvent e) {    
    card.next(c);    
    }    
    
    public static void main(String[] args) {    
        CardLayoutExample2 cl=new CardLayoutExample2();    
        cl.setSize(400,400);    
        cl.setVisible(true);    
        cl.setDefaultCloseOperation(EXIT_ON_CLOSE);    
    }    
}   

Output:

Card Layout

5. GridBag Layout Manager:

The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. The components may not be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells.

Example:

public class GridBagLayoutDemo {  
final static boolean shouldFill = true;  
final static boolean shouldWeightX = true;  
final static boolean RIGHT_TO_LEFT = false;  
  
public static void addComponentsToPane(Container pane) {  
if (RIGHT_TO_LEFT) {  
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);  
}  
  
JButton button;  
pane.setLayout(new GridBagLayout());  
GridBagConstraints c = new GridBagConstraints();  
if (shouldFill) {  
//natural height, maximum width  
c.fill = GridBagConstraints.HORIZONTAL;  
}  
  
button = new JButton("Button 1");  
if (shouldWeightX) {  
c.weightx = 0.5;  
}  
c.fill = GridBagConstraints.HORIZONTAL;  
c.gridx = 0;  
c.gridy = 0;  
pane.add(button, c);  
  
button = new JButton("Button 2");  
c.fill = GridBagConstraints.HORIZONTAL;  
c.weightx = 0.5;  
c.gridx = 1;  
c.gridy = 0;  
pane.add(button, c);  
  
button = new JButton("Button 3");  
c.fill = GridBagConstraints.HORIZONTAL;  
c.weightx = 0.5;  
c.gridx = 2;  
c.gridy = 0;  
pane.add(button, c);  
  
button = new JButton("Long-Named Button 4");  
c.fill = GridBagConstraints.HORIZONTAL;  
c.ipady = 40;      //make this component tall  
c.weightx = 0.0;  
c.gridwidth = 3;  
c.gridx = 0;  
c.gridy = 1;  
pane.add(button, c);  
  
button = new JButton("5");  
c.fill = GridBagConstraints.HORIZONTAL;  
c.ipady = 0;       //reset to default  
c.weighty = 1.0;   //request any extra vertical space  
c.anchor = GridBagConstraints.PAGE_END; //bottom of space  
c.insets = new Insets(10,0,0,0);  //top padding  
c.gridx = 1;       //aligned with button 2  
c.gridwidth = 2;   //2 columns wide  
c.gridy = 2;       //third row  
pane.add(button, c);  
}  
private static void createAndShowGUI() {  
//Create and set up the window.  
JFrame frame = new JFrame("GridBagLayoutDemo");  
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
//Set up the content pane.  
addComponentsToPane(frame.getContentPane());  
  
//Display the window.  
frame.pack();  
frame.setVisible(true);  
}  
  
public static void main(String[] args) {  
javax.swing.SwingUtilities.invokeLater(new Runnable() {  
public void run() {  
createAndShowGUI();  
}  
});  
}  
}  

Output:

GridBag Layout