What are the differences between GridLayout and GridBagLayout in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each component is placed inside a rectangle whereas GridBagLayout is a flexible layout manager that aligns the components vertically and horizontally without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells with each component occupying one or more cells called Component display area.

GridLayout

A GridLayout arranges the components in a rectangular grid. It arranges component in the cells and each cell has the same size. Components are placed in columns and rows. GridLayout(int rows, int columns) takes two parameters that are a column and a row.

Example

import java.awt.*;
import javax.swing.*;
public class GridLayoutTest{
   GridLayoutTest() {
      JFrame frame = new JFrame("GridLayout Test");
      JButton button1, button2, button3, button4;
      button1 = new JButton("Button 1");
      button2 = new JButton("Button 2");
      button3 = new JButton("Button 3");
      button4 = new JButton("Button 4");
      frame.add(button1);
      frame.add(button2);
      frame.add(button3);
      frame.add(button4);
      frame.setLayout(new GridLayout(2,2));
      frame.setSize(300,300);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
   public static void main(String[] args) {
      new GridLayoutTest();
  }
}

Output

GridBagLayout

A GridBagLayout extends the capabilities of the GridLayout. GridBagLayout places component in each individual cell in a grid and also allows the component to span to multiple columns or rows. In order to use GridBagLayout, we need to create a GridBagConstraints object and fill appropriate properties.

Example

import javax.swing.*;
import java.awt.*;
public class GridBagLayoutTest extends JFrame {
   public GridBagLayoutTest() {
      setTitle("GridBagLayout Test");
      setLayout(new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 5;
      gbc.gridy = 0;
      add(new JButton("Button1"), gbc);
      gbc.gridx = 0;
      gbc.gridy = 5;
      add(new JButton("Button2"), gbc);
      gbc.gridx = 2;
      gbc.gridy = 4;
      add(new JButton("Button3"), gbc);
   }
   public static void main(String[] args) {
      GridBagLayoutTest gbcTest = new GridBagLayoutTest();
      gbcTest.setSize(300,300);
      gbcTest.setVisible(true);
      gbcTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

Output

raja
Published on 03-Jul-2019 12:09:35
Advertisements