Java: Grid Layout Manager (swing)

Contributor Icon Contributed by William_Wilson Date Icon February 20, 2006  
Tag Icon Tagged: Java programming

how to use the Grid Layout Manager


Layout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.

+ signs represent empty space.

Grid:
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, 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, and shrinking the frame beyond a resonable size will hide items.

There are 2 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 vertal gaps to place between the items.

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

public GridLayoutManagerExample (String title) {

super(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 -in my opinion- and is even more convenient when used in combination with GridBag Layout.

Questions or Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)

Previous recipe | Next recipe |
 
blog comments powered by Disqus