Advanced Java Programming - Old Questions

6. Why do we need layout management? What is GridBag layout?

5 marks | Asked in 2076

The layout management is used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms. 

GridBagLayout is one of the most flexible — and complex — layout managers the Java platform provides. A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height.Similarly, not all columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be. The way the program specifies the size and position characteristics of its components is by specifying constraints for each component using GridBagConstraints object, as demonstrated below:

import java.awt.Button;  

import java.awt.GridBagConstraints;  

import java.awt.GridBagLayout;   

import javax.swing.*;  

public class GridBagLayoutExample extends JFrame{  

    public static void main(String[] args) {  

            GridBagLayoutExample a = new GridBagLayoutExample();  

        }  

        public GridBagLayoutExample() {  

    GridBagLayoutgrid = new GridBagLayout();  

            GridBagConstraints gbc = new GridBagConstraints();  

            setLayout(grid);  

            setTitle("GridBag Layout Example");  

            GridBagLayout layout = new GridBagLayout();  

    this.setLayout(layout);  

    gbc.fill = GridBagConstraints.HORIZONTAL;  

    gbc.gridx = 0;  

    gbc.gridy = 0;  

    this.add(new Button("Button One"), gbc);  

    gbc.gridx = 1;  

    gbc.gridy = 0;  

    this.add(new Button("Button two"), gbc);  

    gbc.fill = GridBagConstraints.HORIZONTAL;  

    gbc.ipady = 20;  

    gbc.gridx = 0;  

    gbc.gridy = 1;  

    this.add(new Button("Button Three"), gbc);  

    gbc.gridx = 1;  

    gbc.gridy = 1;  

    this.add(new Button("Button Four"), gbc);  

    gbc.gridx = 0;  

    gbc.gridy = 2;  

    gbc.fill = GridBagConstraints.HORIZONTAL;  

    gbc.gridwidth = 2;  

    this.add(new Button("Button Five"), gbc);  

            setSize(300, 300);  

            setPreferredSize(getSize());  

            setVisible(true);  

            setDefaultCloseOperation(EXIT_ON_CLOSE);  

        }  

}