Layout Management in Java

Last Updated on by Sarina Sindurakar

Introduction

Layout manager is an interface which implements the classes of layout manager that controls the size and position of the components in the container. The layout manager object controls the layout of every container object A layout manager uses an algorithm to automatically arrange controls within a window. They’re used to arrange elements in a specific order. The Java Layout Manager help us control the size and positioning of components in GUI forms.

The setLayout() method determines the layout manager.If setLayout() is not called, the default layout manager is used.The general form of setLayout() is:

Void setLayout(Layout Manager layoutObj):

Here,layoutObj is a reference to the desired layout manager.

Some of the most commonly used layout manager in java are:

  • Flow Layout
  • Broder Layout
  • Grid Layout
  • Gridbag Layout
  • Card Layout
  • Group Layout

Types of Layout Management

Flow Layout

It is the container Panel’s and Applets’ default layout manager. It arranges components in a single row, starting in a new row if the container is too narrow.Components are arranged from upper left to lower right, and top to bottom.When there are no more components that will fit on a line, the following component will appear on the next line.

Constructor:

FlowLayout():Creates a flow arrangement with centered alignment and a default horizontal and vertical gap of 5 units.

FlowLayout(int align): generates a flow layout with the specified alignment and a 5-unit horizontal and vertical gap as a default.

FlowLayout(int align, int hgap, int vgap):Creates a flow layout with the specified alignment and horizontal and vertical gaps .

Constants for Alignments:

Static int CENTER:This value indicates that  each row of components should be centered.

Static int LEFT:This value indicates that  each row of components should be left justified.

Static int RIGHT:This value indicates that  each row of components should be right-justified.

Static int LEADING:This value indicates that  each row of components should be  justified to the leading edge of the container’s orientation.

Static int TRAILING:This value indicates that  each row of components should be  justified to the trailing edge of the container’s orientation.

Example:

Layout Management in Java

Output:

Layout Management in Java

Border Layout

Borderlayout is the frame or window’s default layout. The BorderLayout is used to organize the components into five distinct regions: north, south, east, west, and center. Each area may only have one component. The four sides are labeled north, south, east, and west. The center is the area in the middle. The regions to the north, south, east, and west have fixed widths, whereas the center has a variable width.

Constructor:

BorderLayout():Creates border layout but with no gaps between the components.

BorderLayout(int horz_gap, int vert_gap):Creates a border layout with the specified horizontal and vertical gaps between components.

Constants for Alignments:

  • BorderLayout.CENTER
  • BorderLayout.EAST
  • BorderLayout.WEST
  • BorderLayout.NORTH
  • BorderLayout.SOUTH

Example:

Layout Management in Java

Output:
Layout Management in Java

Grid Layout

It organizes the components in a two-dimensional grid. It simply creates a collection of equal-sized components and arranges them in the desired number of rows and columns. A cell can only contain one component. All components are of equal size and cover the entire volume of the container. When the container is resized, all cells are resized as well. The order in which the components are placed in a cell is determined as they are added. Components are added from the first row to the last row and from the first column to the last column.

Constructor:

GridLayout():It creates a grid layout with one column per component in a row.

GridLayout(int rows,int cols):Creates a grid layout with the given rows and columns but ni gaps between the components.

GridLayout(int rows,int cols,int horz_gap,int vert_gap):It creates a grid layout with the given rows and columns along with given horizontal and vertical gaps.

If the value of parameter rows and cols is zero then it indicates an infinite number of rows and columns.

Example:

Layout Management in Java

Output:

Layout Management in Java

GridBagLayout

The gridbag layout is a flexible layout manager that aligns components vertically  and horizontally,without requiring that the components be of the same size.It  maintains a dynamic rectangular grid of cells with each component occupying one or more cells.Each components managed by a grid bag layout is associated with  an instance of GridBagConnstraints that  specifies how the component is arranges within its display area.

Constructor

GridBagLayout():Creates a grid bag layout manager.

We can customize GridBagConstrainsts object by setting one or more of its instance variables:

  • gridx, gridy: For specifying grid location by defining x and y coordinate values.
  • gridwidth ,gridheight: Used to specify the number of grids that will span a document.When the component size is greater than the area, fill is used (i.e. VERTICAL or HORIZONTAL).
  • ipadx, ipady: For defining component width and height, i.e., increasing component size.
  • insets: Used to define the component’s surrounding space, such as top, left, right, and bottom.
  • Anchor: Used when the component size is less than the area, i.e., where to place in a grid.

Example:

package project3;

//Java program to demonstrate GridBagLayout class.

import java.awt.*;

import java.awt.event.*;

import javax.swing.JFrame;

import javax.swing.*;

//class extends JFrame

public class GridbagDemo extends JFrame {

GridbagDemo()

{

// Function to set title of JFrame.

setTitle(“GridBagLayoutDemo”);

// Creating Object of Jpanel class

JPanel p = new JPanel();

// set the layout

p.setLayout(new GridBagLayout());

// creates a constraints object

GridBagConstraints c = new GridBagConstraints();

// insets for all components

c.insets = new Insets(2, 2, 2, 2);

// column 0

c.gridx = 0;

// row 0

c.gridy = 0;

// increases components width by 10 pixels

c.ipadx = 15;

// increases components height by 50 pixels

c.ipady = 50;

// constraints passed in

p.add(new JButton(“Java Swing”), c);

// column 1

c.gridx = 1;

// increases components width by 70 pixels

c.ipadx = 90;

// increases components height by 40 pixels

c.ipady = 40;

// constraints passed in

p.add(new JButton(“Layout”), c);

// column 0

c.gridx = 0;

// row 2

c.gridy = 1;

// increases components width by 20 pixels

c.ipadx = 20;

// increases components height by 20 pixels

c.ipady = 20;

// constraints passed in

p.add(new JButton(“Manager”), c);

// increases components width by 10 pixels

c.ipadx = 10;

// column 1

c.gridx = 1;

// constraints passed in

p.add(new JButton(“Demo”), c);

// Creating Object of “wndcloser”

// class of windowlistener

WindowListener wndCloser = new WindowAdapter() {

public void windowClosing(WindowEvent e)

{

// exit the system

System.exit(0);

}

};

// add the actionwindowlistener

addWindowListener(wndCloser);

// add the content

getContentPane().add(p);

// Function to set size of JFrame.

setSize(600, 400);

// Function to set visibility of JFrame.

setVisible(true);

}

// Main Method

public static void main(String[] args)

{

// calling the constructor

new GridbagDemo();

}

}

Output:

Layout Management in Java

Card Layout

The card layout manager shows the contents we provide it as cards, using distinct layout managers for each container. At any given time, just one card is displayed, and the container acts as a stack of cards. We can assign each card a name and use the show technique to move from card to card.

Constructor:

CardLayout():it creates a new card layout with gaps of size zero.

CardLayout(int hgap, int vgap):it creates a new card layout with the specified horizontal and vertical gaps.

Once ,we have created a deck of cards,our program activates a  card by calling one of the following methods defined by CardLayout:

  •  Void first(Container deck)
  • Void last(Container deck)
  •  Void next(Container deck)
  • Void previous(Container deck)
  •  Void show(Container deck,String cardName)

Example:

package swings_2;

import java.awt.*;   

 import java.awt.event.*; 

 class CardLayoutExample extends Frame implements ActionListener 

 { 

      CardLayout card = new CardLayout(20,20); 

      CardLayoutExample() 

      { 

          setLayout(card); 

          Button Btnfirst = new Button(“Blue “); 

          Button BtnSecond = new Button (“Red”); 

          Button BtnThird = new Button(“GREEN”); 

          add(Btnfirst,”Card1″); 

          add(BtnSecond,”Card2″); 

          add(BtnThird,”Card3″); 

          Btnfirst.addActionListener(this); 

          BtnSecond.addActionListener (this); 

          BtnThird.addActionListener(this); 

      } 

      public void actionPerformed(ActionEvent e) 

      { 

        card.next(this); 

      } 

 } 

    class CardLayoutJavaExample 

    { 

         public static void main(String args[]) 

        { 

             CardLayoutExample frame = new CardLayoutExample(); 

             frame.setTitle(“CardLayout in Java Example”); 

             frame.setSize(220,150); 

             frame.setResizable(false); 

             frame.setVisible(true); 

        } 

    } 

Group Layout 

Group Layout is a layout manager that was developed for use by GUI builder tools,but it can also be used manually.GroupLayout works with the horizontal and vertical layouts separately.

The layout is defined separately for each dimension. Each component, however, must be defined twice in the layout. When defining the horizontal layout, we don’t need to care about the vertical dimensions, and vice versa.When we concentrate on a single dimension, we only have to solve half of the problem at a time. This is more convenient than dealing with both dimensions at the same time. Of course, this means that each component must be defined twice in the layout.Components that are parallel in one dimension are usually ordered in the other.Layout groupings are defined by GroupLayout.A group can be sequential or parallel, and it can include components and other groups.

Example:

package swings_2;

///Java Program to illustrate the GroupLayout class

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class GroupLayoutDemo {

private JFrame mainFrame;

private JLabel headerLabel, statusLabel, msglabel;

private JPanel controlPanel;

public GroupLayoutDemo()

        {

prepareGUI();

}

public static void main(String[] args)

{

GroupLayoutDemo GroupLayoutDemo = new GroupLayoutDemo();

GroupLayoutDemo.showGroupLayoutDemo();

}

private void prepareGUI()

{

mainFrame = new JFrame(“Java GroupLayout Examples”);

mainFrame.setSize(400, 400);

mainFrame.setLayout(new GridLayout(3, 1));

headerLabel = new JLabel(“”, JLabel.CENTER);

statusLabel = new JLabel(“”, JLabel.CENTER);

statusLabel.setSize(350, 100);

mainFrame.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent windowEvent)

{

System.exit(0);

}

});

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

}

private void showGroupLayoutDemo()

{

headerLabel.setText(“Layout in action: GroupLayout”);

JPanel panel = new JPanel();

panel.setSize(200, 200);

GroupLayout layout = new GroupLayout(panel);

layout.setAutoCreateGaps(true);

layout.setAutoCreateContainerGaps(true);

JButton btn1 = new JButton(“Button 1”);

JButton btn2 = new JButton(“Button 2”);

JButton btn3 = new JButton(“Button 3”);

layout.setHorizontalGroup(layout.createSequentialGroup()

.addComponent(btn1)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)

.addComponent(btn2)

.addComponent(btn3))));

layout.setVerticalGroup(layout.createSequentialGroup()

.addComponent(btn1)

.addComponent(btn2)

.addComponent(btn3));

panel.setLayout(layout);

controlPanel.add(panel);

mainFrame.setVisible(true);

}

}

Output:

Layout Management in Java

No layout Manager

Components can be arranged in containers without the use of a layout manager. Items must be manually positioned and arranged in this case. This layout should be used only if the window will not and cannot be resized, as the items in the window will remain in place. The steps for creating a container without a layout manager are as follows.

Example:

package swing;

import javax.swing.*;

public class layout_find {

    public static void main(String[] args){

        //defining the jframe 

        JFrame f= new JFrame(“Find”);

        JLabel l1=new JLabel(“Find What:”); 

        l1.setBounds(10,10, 80,30); 

        f.add(l1);

        JTextField text = new JTextField(); 

        text.setBounds(80,10, 200,28); 

        f.add(text);

        //defining button 

        JButton b=new JButton(“Find”);

        b.setBounds(290,10,80,25);

        f.add(b);

        JButton c=new JButton(“Cancel”);

        c.setBounds(290,40,80,25);

        f.add(c);

        JCheckBox checkBox1 = new JCheckBox(“Match case”); 

        checkBox1.setBounds(80,40, 100,30);

        f.add(checkBox1);

        JCheckBox c2 = new JCheckBox(“Wrap Around”); 

        c2.setBounds(180,40, 100,30);

        f.add(c2);

        JCheckBox c3 = new JCheckBox(“Whole Words”); 

       c3.setBounds(80,65, 110,30);

        f.add(c3);

        JCheckBox c4 = new JCheckBox(“Search Backwards”); 

        c4.setBounds(189,65, 140,30);

        f.add(c4);

        f.setSize(400,150);

        f.setLayout(null);

        //whether to make jframe visibile or not

         f.setVisible(true);

    }  }

Output:

Layout Management in Java

More From Author

File Handling in JAVA

Introduction To Java Awt, Swing and Applet