GridLayout is a stripe manager A swing that modulates the container into a grid of several squares of the same dimension, each of which is placed in a box. In the code below, we put six buttons in three rows and two columns.
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridLayoutExample extends JFrame{
GridLayout grid = new GridLayout(3, 2);
public GridLayoutExample(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250,250);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.setContentPane(panel);
panel.setLayout(grid);
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));
}
public static void main(String[] args) {
new GridLayoutExample();
}
}
Output
setHgap and setVgap
The method setHgap(int h) changes the horizontal space between two components with an integer value as the parameter.
The setVgap(int v) changes the vertical space between two components with an integer value as a parameter.
GridLayout also has a constructor that passes Hgap and Vgap as arguments:
public gridLayout(int line, int col, int hgap, int vgap);
- row: zero means no row count.
- col: zero means no number of columns.
- hgap: horizontal space.
- vgap: vartical space.
The result after adding these two statements to the previous code:
grid.setHgap(10);
grid.setVgap(15);
getColumnsReturns the number of columns.
getRowsReturns the number of rows.
setColumnsChange the number of columns.
setRowsChange the number of rows.
minimumLayoutSizeDetermines the minimum size (length and height) of rows and columns with the space between widgets.
References:
Site from scratch: gridLayout javaJava2s: How to use GridLayoutenst.fr: Use GridLayout