GridBagLayout is by far the most versatile of all layout managers. As a result, it also requires the most work.

The basic idea is that Constraints are applied to a Container to determine how the Component is placed on the Container.

What Are Constraints?

Constraints control how the component is placed on a container. There are 11 constraints altogether, though I commonly use only 6.

The Constraints

  1. gridx: specifies the x coordinate for the upper-left corner
  2. gridy: specifies the y coordinate for the upper-left corner
  3. gridwidth: specifies the number of columns to span
  4. gridheight: specifies the number of rows to span
  5. fill: specifies how the component fills the area: BOTH, NONE, HORIZONTAL, VERTICAL
  6. anchor: specifies how to position the component in the area: CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST
  7. weightx: specifies how to distribute extra horizontal space
  8. weighty: specifies how to distribute extra vertical space
  9. ipadx: specifies the internal padding to add to the minimum width
  10. ipady: specifies the internal padding to add to the minimum height
  11. insets: specifies the external padding between the component and the edges of its display area

Before You Begin

The Code

I’ve written a method called “gbc” that accepts the first 6 constraints listed above as arguments and returns a GridBagConstraints object.

I usually create my own constants for the GridBagConstraints constants, just for keeping the code smaller.

	cmdCalc = new Button("Calculate");
	gbcLocal = gbc(0, 0, 1, 1, intFillN, intAnchorC);
	gblLocal.setConstraints(cmdCalc, gbcLocal);


The Layout Manager manages the grid for you at display time

The code:

The Applet: