Java Swing GridLayout
Java Swing GridLayout
In this tutorial, you will learn about Java Swing GridLayout. In Java Swing, GridLayout
is a layout manager that arranges components in a rectangular grid. It places components in rows and columns, and each cell in the grid is the same size.
GridLayout uses grid cells to place the components. Each cell is the same size, and each GUI component takes up the same space in a container. When the user resizes the container, the size of the GUI component also changes.
-
All cells are equal size regardless of the component’s preferred size.
-
Components are added row by row, left to right.
-
The number of rows or columns can be fixed, and the other can be set to
0
to allow it to adjust automatically
Constructor Syntax
The constructor syntax is as follows:
- GridLayout(int rows, int cols)
- GridLayout(int rows, int cols, int hgap, int vgap)
rows: Number of rows in the grid.
cols: Number of columns in the grid.
hgap: Horizontal space between components.
vgap: Vertical space between components.
Java Demo Program
/**************************************** * * Filename: GridLayoutDemo.java * Java Tutorials - www.TestingDocs.com * *****************************************/ import java.awt.*; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class GridLayoutDemo { // main method public static void main(String[] args) { // Create a Frame JFrame frame = new JFrame("GridLayout -www.TestingDocs.com"); JButton btn0 = new JButton("0"); JButton btn1 = new JButton("1"); JButton btn2 = new JButton("2"); JButton btn3 = new JButton("3"); JButton btn4 = new JButton("4"); JButton btn5 = new JButton("5"); JButton btn6 = new JButton("6"); JButton btn7 = new JButton("7"); JButton btn8 = new JButton("8"); JButton btn9 = new JButton("9"); JButton btnC = new JButton("C"); JButton btnEquals = new JButton("="); // Create grid layout :with 4 rows , 3 columns JPanel panel = new JPanel(new GridLayout(4,3,10,10)); // add buttons panel.add(btn0); panel.add(btn1); panel.add(btn2); panel.add(btn3); panel.add(btn4); panel.add(btn5); panel.add(btn6); panel.add(btn7); panel.add(btn8); panel.add(btn9); panel.add(btnC); panel.add(btnEquals); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600,400); frame.getContentPane().add(panel); frame.setVisible(true); } }
Output
Run the Java application to view the output.
—
Java Tutorial on this website: