javacodex.com
Java Examples
Java Examples
memu home questions

GridLayout

A GridLayout arranges components in a rectangular grid of equally sized cells. Each component is placed in exactly one cell. It does not respect the preferred size of the component. It divides the available space into equally sized cells and resizes each component to the cell’s size.

You can specify either the number of rows or the number of columns in the grid. If you specify both, only the number of rows is used, and the number of columns is computed.

Source: (GridLayoutExample.java)

import java.awt.*;
import javax.swing.*;
 
public class GridLayoutExample {
 
  public static void main(String[] arguments) {
 
    // main window
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("GridLayoutExample Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(250,250); 
 
    // set main window from to use GridLayout
    frame.setLayout(new GridLayout(3,3));
 
    // add a bunch of stuff to the frame
    frame.add(new JButton("B1"));
    frame.add(new JLabel("L1"));
    frame.add(new JButton("B2"));
    frame.add(new JLabel("L2"));
    frame.add(new JButton("B3"));
    frame.add(new JLabel("L3"));
    frame.add(new JButton("B4"));
    frame.add(new JLabel("L4"));
    frame.add(new JButton("B5"));
 
    frame.setVisible(true);
  }
}
 

Output:

$ java GridLayoutExample
Output



Contact: javacodex@yahoo.com