Thursday, 14 May 2015

GridLayout in Java

GridLayout's simple rule is to allow the user to define the number of rows and columns in the layout. GridLayout then sticks one item in each grid cell. The cells are all the same size. The size of the cells is determined by the number of cells and the size of the container

Listing 17.28. Using the GridLayout Manager.
import java.awt.*;
import java.applet.Applet;


public class gridlayout extends Applet{
    Button the_buttons[];

    public void init()
    {   int i;
        int n_buttons; 
        GridLayout gl; 
        String name;

        //set up a grid that is 3 rows and 10 columns. There is a 10 pixel space
        //between rows and 15 pixels between columns
        gl = new GridLayout(3,10,10,15); 
        setLayout(gl); 
        n_buttons = 30; 
        the_buttons = new Button[n_buttons];
        for(i=0;i<n_buttons;i++) {
            name = "Button " + i;
            the_buttons[i] = new Button(name);
            add(the_buttons[i]); 
        }
    }

}

As you see in this listing, the GridLayout creator method enables you to define gaps between components.
There are two GridLayout creator methods:
new GridLayout(int rows, int cols)
Makes a GridLayout with the specified number of rows and columns.
new GridLayout(int rows, int cols, int horizontal_gap, int vertical_gap)
Makes a GridLayout with the specified rows and columns and with the specified empty space around each component.  

No comments:

Post a Comment