Learning Java
Custom Search

Previous Next

Grid Layout

With the GridLayout you specify the number of rows and columns. Then the components are added from left to right. When the row becomes full, the next row is started.

After testing the code below, be sure to increase and decrease the size of the window. In this case, you will see the sizes changing for the components instead of the positions, as you saw with the FlowLayout.

The format of the constructor is (last 2 parameters are optional).

    GridLayout(int rows, int cols, int horizontal_gap, int vertical_gap)

Test modifying the parameter list from

    GridLayout nature = new GridLayout(3, 3, 10, 10);
    to
    GridLayout nature = new GridLayout(3, 3);

Notice the spacing changes between each button.

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

public class AnimalGrid extends JFrame {
    JButton dog = new JButton("Dog");
    JButton cat = new JButton("Cat");
    JButton bird = new JButton("Bird");
    JButton pig = new JButton("Pig");
    JButton mouse = new JButton("Mouse");
    JButton lion = new JButton("Lion");
    JButton tiger = new JButton("Tiger");
    JButton bear = new JButton("Bear");
    JButton deer = new JButton("Deer");

    public AnimalGrid() {
        super("Animal GridLayout");
        setSize(260, 260);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pane = new JPanel();
        GridLayout nature = new GridLayout(3, 3, 10, 10);
        pane.setLayout(nature);
        pane.add(dog);
        pane.add(cat);
        pane.add(bird);
        pane.add(pig);
        pane.add(mouse);
        pane.add(lion);
        pane.add(tiger);
        pane.add(bear);
        pane.add(deer);
        add(pane);
        setVisible(true);
    }

    public static void main(String[] arguments) {
        AnimalGrid frame = new AnimalGrid();
    }
}

 

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved