Tuesday, November 5, 2013


GridBagLayout is a layout manager in AWT package. It is more complex than GridLayout. But it is more powerful or flexible than GridLayout. By using the GridBagLayout, you can have different components of different sizes in a single row or column. When you arrange components on a container, you do not need to specify the number of rows or columns. Instead, you will need to specify the constraints or rules by using the GridBagContraints class. These constraints help GridBagLayout to place the components in the proper places on the container. Below are common constraints used in setting up the grid.

fill allows the components to resize automatically when the row or column expanded or thrinked.
gridwidth specifies the number of columns in the area to display the component.
gridheight specifies the number of rows in the area to display the component.
gridx specifies the column in the grid to display the component. Its value starts from 0 (first column).
gridy specifies the row in the grid to display the component. Its value starts from 0 (first row).

Example: The following code below arranges the components on the JFrame window as shown in the picture.


import java.awt.Container;
import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class GridBagLayoutManager {
public static void main(String[] args){
JFrame jf=new JFrame("GridBagLayout");
Container container=jf.getContentPane();
GridBagLayout gb=new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
JButton bt1=new JButton("Button 1");
JButton bt2=new JButton("Button 2");
//fill components in cells
gc.fill = GridBagConstraints.BOTH;
        gb.setConstraints(bt1, gc);
        gc.gridwidth = GridBagConstraints.REMAINDER;
        gb.setConstraints(bt2, gc);

//add JTextArea, Button 3, and Button 4 to the second row

JTextArea ja=new JTextArea(10,10);
ja.setText("GridBagLayout is a layout manager that is more powerful than the GridLayout manager.");
JButton bt3=new JButton("Button 3");
JButton bt4=new JButton("Button 4");
//expand row and column
gc.gridwidth =2; //2 columns
gc.gridheight =3;//3 rows      
gb.setConstraints(ja, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
//reset row and column
gc.gridwidth =1;
gc.gridheight = 1;
gb.setConstraints(bt3, gc);
gc.gridy=2; //Add the Button 4 below the Button 3
gb.setConstraints(bt4, gc);




1 comment: