Java: Grid Layout Manager (Swing)

Posted February 20, 2006 by William_Wilson in Java programming

This tutorial describes using the Grid Layout Manager.

Layout Managers are used in the organization of Panels and Frames. The proper layout should be chosen to accommodate frame resizing and use.

The + signs represent empty space.

This Layout is useful for aligning elements or items onto a grid. The items will be added left to right across each row and continuing at the beginning of the next row. This is similar to that of the Flow layout. This layout does have the draw back that the NULL layout does, as it aligns items according to a set size of rows and columns. Shrinking the frame beyond a reasonable size will hide items.

There are two constructors:
public GridLayout(int rows, int columns)
-which takes only the rows and columns you wish to have mapped out
public GridLayout(int rows, int columns, int hGap, int vGap) throws IllegalArgumentException;
-which takes the rows and columns to be mapped out as well as the horizontal and vertical gaps to place between the items

CODE Example:
import java.awt.*;
import javax.swing.*;
public class GridLayoutManagerExample extends JFrame {

public GridLayoutManagerExample (String title) {

Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(3,4,5,5));

// Add radio buttons. Use a ButtonGroup to ensure only one
// RadioButton is on at a time
ButtonGroup aButtonGroup = new ButtonGroup();
JRadioButton aButton;
for (int buttonNumber = 1; buttonNumber <= 12; buttonNumber++){ aButton = new JRadioButton(String.valueOf(buttonNumber)); aButtonGroup.add(aButton); contentPane.add(aButton); } } public static void main(String args[]) { GridLayoutManagerExample frame = new GridLayoutManagerExample("Example"); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setSize(500, 300); frame.setVisible(true); }} *Since we have grid layout handling the placement of the buttons, the difficulty of aligning is done for us. This is included upon resizing the window. *NOTE: This frame's buttons do not actually do anything. This is simply an example of using the layout manager. -Try changing the fram.setResizable to true, and resize the frame. *Grid Layout manager is one of the most useful and is even more convenient when used in combination with GridBag Layout.

Questions or Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.

Comments are closed.