Credits

Wednesday, September 15, 2010

Java's Grid Layout

Another commonly used layout manager is the Grid Layout. If you want your components in rows and columns, then, a Grid Layout is used.

The sizes of the components are adjusted to fit inside the container. A Grid Layout requires you to set the number of rows and columns and even the gaps among these components.

The program below illustrates this example.

[+/-] show/hide


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

public class GridLayoutDemo extends JFrame {
Container con = getContentPane();
public GridLayoutDemo()
{

JButton b1,b2,b3,b4,b5;

con.setLayout(new GridLayout(2,3,10,1)); // where 2=rows,3=columns,10=hgap,1=vgap
b1 = new JButton("Button1");
b2 = new JButton("Button2");
b3 = new JButton("Button3");
b4 = new JButton("Button4");
b5 = new JButton("Button5");

con.add(b1);
con.add(b2);
con.add(b3);
con.add(b4);
con.add(b5);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main (String [] args){
GridLayoutDemo frm = new GridLayoutDemo();
frm.setSize(300,100);
frm.setTitle("Grid Layout Demo");
frm.setVisible(true);
}
}

AddThis