JPanel - How to use a GridLayout in java
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.
Returns the number of columns.
getRows
Returns the number of rows.
setColumns
Change the number of columns.
setRows
Change the number of rows.
minimumLayoutSize
Determines the minimum size (length and height) of rows and columns with the space between widgets.
References:
Site from scratch: gridLayout java
Java2s: How to use GridLayout
enst.fr: Use GridLayout
import java.awt.GridLayout;Output
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();
}
}
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:
getColumns- 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);
Returns the number of columns.
getRows
Returns the number of rows.
setColumns
Change the number of columns.
setRows
Change the number of rows.
minimumLayoutSize
Determines the minimum size (length and height) of rows and columns with the space between widgets.
References:
Site from scratch: gridLayout java
Java2s: How to use GridLayout
enst.fr: Use GridLayout