Below is the Java swing example of creating a GridLayout’s container that contains buttons in it. The grid layout container will adjust the alignment of those buttons after either the value of the number of rows or the number of columns has been specified : GridLayout(int rows, int columns, int hgap, int vgap), hgap and vgap are the horizontal and vertical gaps of a cell, each cell contains one button.
import javax.swing.*; import java.awt.*; public class GridLayoutDemo { public static void main(String[] args) { JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); Container pane = frame.getContentPane(); JPanel buttonpanel = new JPanel(); buttonpanel.setLayout(new GridLayout(3, 0,10,10)); for(int i=1; i < 10; i++) { buttonpanel.add(new Button("Button" + i)); } pane.add(buttonpanel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
The above program will create the following outcomes:-