Previous | Next | Trail Map | Creating a GUI with JFC/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.

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.

GridBagLayout is the most flexible -- and complex -- layout manager the Java platform 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 rectangles (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 bottom row, which contains Button 5, gets all the new vertical space. 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 all the available horizontal space. 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 Example Explained

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

Examples that Use GridBagLayout

You can find examples of using GridBagLayout throughout this tutorial. The follwing table lists a few.

Example Where Described Notes
GridBagWindow.java This page Uses many features -- weights, insets, internal padding, horizontal fill, exact cell positioning, multi-column cells, and anchoring (component positioning within a cell).
TextSamplerDemo.java Using Swing's Text Components(in the Creating a User Interface trail) Aligns two pairs of labels and text fields, plus adds a label across the full width of the container.
ContainerEventDemo.java How to Write a Container listener(in the Creating a User Interface trail) Positions five components within a container, using weights, fill, and relative positioning.


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Laying Out Components Within a Container