gridlayout in java

ww‮gi.w‬iftidea.com

GridLayout is a layout manager in Java that arranges components in a grid of rows and columns. Each component occupies one cell in the grid.

To use a GridLayout, you first need to create a new instance of the layout manager and set it as the layout manager for a container. Here's an example of how to create a GridLayout with 3 rows and 2 columns:

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JButton;

public class GridLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("GridLayout Example");
        frame.setLayout(new GridLayout(3, 2)); // create a new GridLayout with 3 rows and 2 columns

        JButton button1 = new JButton("Button 1");
        JButton button2 = new JButton("Button 2");
        JButton button3 = new JButton("Button 3");
        JButton button4 = new JButton("Button 4");
        JButton button5 = new JButton("Button 5");
        JButton button6 = new JButton("Button 6");

        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);

        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we create a new JFrame and set its layout manager to a new GridLayout with 3 rows and 2 columns. We then create six JButton components and add them to the frame. The components are added to the container in row-major order, which means they are added in the order (0,0), (0,1), (1,0), (1,1), (2,0), (2,1).

Finally, we call pack() to resize the frame to fit its components, and setVisible(true) to make it visible. When we run this example, we'll see a frame with six buttons arranged in a 3x2 grid.