Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Laying Out Components within a Container

How to Use GridBagLayout

Here's an applet that shows a GridBagLayout(in the API reference documentation) in action.

Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up:

Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go to example-1dot1/GridBagWindow.html.

GridBagLayout is the most flexible -- and complex -- layout manager the AWT provides. As the above applet shows, a GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height. Similarly, not all columns necessarily have the same width. Essentially, GridBagLayout places components in squares (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be.

If you enlarge the window (as shown above), you'll notice that the last row gets all the new vertical space, and that the new horizontal space is split evenly among all the columns. This resizing behavior is based on weights the applet assigns to individual components in the GridBagLayout. You'll also notice that each component takes up as much space as it can. This behavior is also specified by the applet.

The way the applet specifies the size and position characteristics of its components is by specifying constraints for each component, To specify constraints, you set instance variables in a GridBagConstraints object and tell the GridBagLayout (with the setConstraints() method) to associate the constraints with the component.

The following pages explain the constraints you can set and provide examples of setting them.

Specifying Constraints

This page tells you what instance variables GridBagConstraints has, what values you can set them to, and how to associate the resulting GridBagConstraints with a Component.

The Applet Example Explained

This page puts it all together, explaining the code for the applet on this page.

More GridBagLayout Examples

You can find more examples of using GridBagLayout throughout this tutorial. Here are a few programs that use GridBagLayout:

Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Laying Out Components within a Container