Laying Out Components within a Container |
Here's an applet that shows aGridBagLayout
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 viewGridBag.html
, specifyingswing.jar
in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.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
is the most flexible -- and complex -- layout manager the AWT provides. AGridBagLayout
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.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 theGridBagLayout
(with thesetConstraints
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 variablesGridBagConstraints
has, what values you can set them to, and how to associate the resultingGridBagConstraints
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 usingGridBagLayout
throughout this tutorial. Here are a few programs that useGridBagLayout
:[PENDING: redo this list with Swing examples]
- 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.
- ShowDocument.java, which you can see running in Displaying Documents in the Browser.
Laying Out Components within a Container |