Previous | Next | Trail Map | Creating a User Interface | 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:

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 the applet brings up, 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 | Laying Out Components within a Container