GridLayout
is a layout manager in Java that arranges components in a grid of rows and columns. It allows you to specify the number of rows and columns in the grid, and how components should be placed within the grid cells.
Here's an example of how you can use GridLayout
to create a simple grid of buttons:
import java.awt.*; import javax.swing.*; public class GridLayoutExample extends JFrame { public GridLayoutExample() { setLayout(new GridLayout(2, 3)); add(new JButton("Button 1")); add(new JButton("Button 2")); add(new JButton("Button 3")); add(new JButton("Button 4")); add(new JButton("Button 5")); add(new JButton("Button 6")); pack(); setVisible(true); } public static void main(String[] args) { new GridLayoutExample(); } }
This code creates a JFrame
with a GridLayout
that has 2 rows and 3 columns. It then adds 6 buttons to the frame, which will be arranged in the grid.
You can customize the GridLayout
by setting various options, such as the horizontal and vertical gap between cells, the size of the cells, and the alignment of the components within the cells.