[an error occurred while processing this directive]

Create Layout Components in a Grid in Java

                         

In this section, you will learn how to create layout components with the help of grid in Java Swing. The grid layout provides the facility to arrange some created GUI components for the frame. The grid layout arranges components by dividing areas into rows and columns.

This program shows grid layout components added for panel on the frame. There are five components like labels, text boxes and command buttons. These are situated on the panel in a specific locations or areas. This program also mention the position of every component on the panel an gap from one - another. Following methods and APIs have been used for creating a grid layout components for arranging components used for the appropriate result.

GridLayout(int rows, int columns, int horizontal_gap, int vertical_gap):
This is the constructor of GridLayout class. This is class is imported from the java.awt.*; package. It is used for the creating Layout for making suitable GUIs. It's constructor takes some argument for arranging components on the panel for the frame or application window. This constructor takes following arguments:

  • First is the row number where the specified component starts.
  • Second is the column number from where the components starts for arranging.
  • Third is the horizontal gap between components.
  • And last is the vertical gap between components.

This constructor takes all the integer value as parameters.

Here is the code of program:

import javax.swing.*;
import java.awt.*;

public class GrideComponents{
  public static void main(String[] args) {
    JFrame frame = new JFrame("Laying Out Components in a Grid");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(5,2,20,50));
    panel.add(new JLabel("Enter name"));
    panel.add(new JTextField(5));
    panel.add(new JLabel("Enter Roll"));
    panel.add(new JTextField(3));
    panel.add(new JLabel("Enter Class"));
    panel.add(new JTextField(3));
    panel.add(new JLabel("Enter Total Marks"));
    panel.add(new JTextField(3));
    panel.add(new JButton("Ok"));
    panel.add(new JButton("Cancel"));
    frame.add(panel);
    frame.setSize(400,400);
    frame.setVisible(true);
  }
}

Screen shot for the result of the above program:

Arranged several components in a Grid component

Download this example

                         

[an error occurred while processing this directive]