Previous | Next | Trail Map | Creating a User Interface (with Swing) | 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 the preceding applet runs using Java Plug-in 1.1.1, it is a Swing 1.0.3 version of the applet. To run the Swing 1.1 Beta 3 version of the applet, you can use the JDK Applet Viewer to view GridBag.html, specifying swing.jar in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.

GridBagLayout is the most flexible -- and complex -- layout manager the AWT provides. 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 program 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 program.

The way the program 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.

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 program on this page.

Examples that Use GridBagLayout

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

[PENDING: redo this list with Swing examples]


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