Laying Out Components within a Container |
Here's an applet that shows a GridBagLayout in action.
GridBagLayout is the most flexible -- and complex -- layout manager the AWT provides. As the above applet shows, a GridBagLayout places components in rows and columns, allowing specified components to span multiple rows or columns. 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 simple programs that use GridBagLayout:
- DialogWindow.java, for a dialog which you can bring up from the applet in How to Use Dialogs.
- ListDemo.java, which you can see running in How to Use Lists.
- TextDemo.java, which you can see running in How to Use TextAreas and TextFields.
- CoordinatesDemo.java and RectangleDemo.java, which you can see running in Drawing Shapes.
Laying Out Components within a Container |