The GridLayout manager does approximately what you might expect. It divides the surface area up into a grid and when you add components it places them one after the other from left to right, top to bottom. Unlike the BorderLayout and FlowLayout it ignores any preferred size of the component. For example the preferred size of a button will be wide enough to show its text. The FlowLayout manager attempts to ensure that a button is this preferred size. The GridLayout has a more bondage and discipline approach. The only thing it cares about is making sure the component fits into the grid.

The following code lays out a set of buttons within a Frame using a GridLayout that has been set up to have 2 rows and 5 columns.

import javax.swing.*;
import java.awt.*;

public class GridAp extends JFrame{

public static void main(String argv[]){
      GridAp ga=new GridAp();
    	//Setup GridLayout with 2 rows and 5 columns
	ga.getContentPane().setLayout(new GridLayout(2,5));
        getContentPane().add(new JButton("One"));
        getContentPane().add(new JButton("Two"));
        getContentPane().add(new JButton("Three"));
        getContentPane().add(new JButton("Four"));
        getContentPane().add(new JButton("Five"));
        getContentPane().add(new JButton("Six"));
        getContentPane().add(new JButton("Seven"));
        getContentPane().add(new JButton("Eight"));
        getContentPane().add(new JButton("Nine"));
        getContentPane().add(new JButton("A very long button label indeed"));
        }//End of constructor

}//End of Application

Last modified: Thursday, 24 July 2014, 2:54 PM