HomeComputer programmingJava programmingJava: Grid Layout Manager (Swing)

Java: Grid Layout Manager (Swing)

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.

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. 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) {

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

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

RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android