How to Use GridBagLayout

 <  Day Day Up  >  

Here's a picture of an example that uses GridBagLayout . [16]

[16] GridBagLayout API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GridBagLayout.html.

Figure 17. A simple GUI that uses GridBagLayout .

graphics/08fig20.gif

graphics/cd_icon.gif

You can run GridBagLayoutDemo using Java Web Start or compile and run the example yourself. [17]

[17] To run GridBagLayoutDemo using Java Web Start, click the GridBagLayoutDemo link on the RunExamples/layout.html page on the CD. You can find the source files here: JavaTutorial/uiswing/layout/example-1dot4/index.html#GridBagLayoutDemo .

GridBagLayout is one of the most flexible ”and complex ”layout managers the Java platform provides. It 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, and not all columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles (cells) in a grid and then uses their preferred sizes to determine how big the cells should be.

Figure 18 shows the grid for the preceding example, GridBagLayoutDemo . As you can see, the grid has three rows and three columns. The button in the second row spans all the columns; the button in the third row spans the two right columns. If you enlarge the window, you'll notice that the bottom row, which contains button 5, gets all of the new vertical space; the new horizontal space is split evenly among all columns. This resizing behavior is based on weights the program assigns to individual components in GridBagLayout . Also notice that each component takes up all of the available horizontal space ”but not (as you can see with button 5) all of the available vertical space. This behavior is also specified by the program.

Figure 18. The GridBagLayout application with the three rows and three columns highlighted.

graphics/08fig21.gif

The program specifies the size and position of its components by specifying constraints for each one. To specify constraints, you set instance variables in a GridBagConstraints object and tell GridBagLayout (either with the setConstraints method or when adding the component to its container) to associate the constraints with the component.

The sections that follow explain the constraints you can set and provide examples.

Specifying Constraints

The following code is typical of what goes in a container that uses GridBagLayout . You'll see a more detailed example in the next section.

 JPanel pane = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //For each component to be added to this container:  //...Create the component...   //...Set instance variables in the GridBagConstraints instance...  pane.add(theComponent, c); 

You can reuse the same GridBagConstraints instance for multiple components, even if the components have different constraints. GridBagLayout extracts the constraint values and doesn't use the GridBagConstraints instance again. Be careful, however, to reset the GridBagConstraints instance variables to their default values when necessary.

Note: The following discussion assumes that GridBagLayout controls a container that has a left-to-right component orientation. A right-to-left orientation causes the GridBagLayout to adjust cell locations and spacing accordingly .


You can set the following GridBagConstraints instance variables:

gridx, gridy

Specifies the row and column at the upper left of the component. The leftmost column has address gridx=0 and the top row has address gridy=0 . Use the default value GridBagConstraints.RELATIVE to specify that the component be placed just to the right of (for gridx ) or just below (for gridy ) the component that was added to the container just before this one was added. We recommend specifying the gridx and gridy values for each component; this tends to result in more predictable layouts.

gridwidth, gridheight

Specifies the number of columns (for gridwidth ) or rows (for gridheight ) in the component's display area. These constraints specify the number of cells the component uses, not the number of pixels. The default value is 1. Use GridBagConstraints.REMAINDER to make the component be the last one in its row (for gridwidth ) or column (for gridheight ). Use GridBagConstraints.RELATIVE to make the component the next-to-last one in its row (for gridwidth ) or column (for gridheight ).

Note: GridBagLayout doesn't allow a component to span multiple rows unless the component is in the leftmost column or you've specified positive gridx and gridy values for it.


fill

Used when the component's display area is larger than its requested size to determine whether and how to resize it. Valid values (defined as GridBagConstraints constants) are NONE (the default), HORIZONTAL (make the component wide enough to fill its display area horizontally, but don't change its height), VERTICAL (make the component tall enough to fill its display area vertically, but don't change its width), and BOTH (make the component fill its display area entirely).

ipadx , ipady

Specifies the internal padding, that is, how much to add to the minimum size of the component. The default value is 0. The width will be at least the component's minimum width plus ipadx*2 pixels, since the padding applies to both sides of the component. Similarly, the height will be at least the component's minimum height plus ipady*2 pixels.

insets

Specifies the external padding of the component ”the minimum amount of space between it and the edges of its display area. The value is an Insets object. By default, a component has no external padding.

anchor

Used to determine where (within a component's display area) to place the component when it is smaller than the area. Valid values (defined as GridBagConstraints constants) are CENTER (the default), PAGE_START , PAGE_END , LINE_START , LINE_END , FIRST_LINE_START , FIRST_LINE_END , LAST_LINE_END , and LAST_LINE_START . (See Figure 19.)

Figure 19. Interpretation of the GridBagConstraints anchor constants in a container that has the default left-to-right component orientation.

graphics/08fig22.gif

Version Note: The PAGE_* and *LINE_* constants were introduced in v1.4. Previous releases required values named after points of the compass ”for example, NORTHEAST for the top-right of the display area. We recommend using the new constants since they enable easier localization.


weightx , weighty

Specifies weights used to distribute space among columns ( weightx ) and among rows ( weighty ); this is important for specifying resizing behavior. Unless you specify at least one nonzero value for weightx or weighty , all of the components clump together in the center of their container. This is because a weight of 0.0 (the default) puts any extra space between the container's grid of cells and its edges.

Generally weights are specified with 0.0 and 1.0 as the extremes, with the numbers in between used as necessary. Larger numbers indicate that the component's row or column should get more space. For each column, the weight is related to the highest component weightx specified within it, with each multicolumn component's weight split between the columns. Similarly, each row's weight is related to the highest weighty specified for a component within that row. Extra space tends to go toward the rightmost column and bottom row.

The next section discusses constraints in the context of the example program.

The Example Explained

Figure 20 is another picture of the GridBagLayoutDemo application.

Figure 20. A simple GUI that uses GridBagLayout .

graphics/08fig23.gif

The following code creates the GridBagLayout and the components it manages . You can find the entire source file in GridBagLayoutDemo.java . [18]

[18] You can find the source file here: JavaTutorial/uiswing/layout/example-1dot4/index.html #GridBagLayoutDemo .

 JButton button; pane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; button = new JButton("Button 1"); c.weightx = 0.5; c.gridx = 0; c.gridy = 0; pane.add(button, c); button = new JButton("Button 2"); c.gridx = 1; c.gridy = 0; pane.add(button, c); button = new JButton("Button 3"); c.gridx = 2; c.gridy = 0; pane.add(button, c); button = new JButton("Long-Named Button 4"); c.ipady = 40;      //make this component tall c.weightx = 0.0; c.gridwidth = 3; c.gridx = 0; c.gridy = 1; pane.add(button, c); button = new JButton("5"); c.ipady = 0;       //reset to default c.weighty = 1.0;   //request any extra vertical space c.anchor = GridBagConstraints.PAGE_END; //bottom of space c.insets = new Insets(10,0,0,0);  //top padding c.gridx = 1;       //aligned with button 2 c.gridwidth = 2;   //2 columns wide c.gridy = 2;       //third row pane.add(button, c); 

The preceding example uses one GridBagConstraints instance for all of the components the GridBagLayout manages. Just before each component is added to the container, the code sets (or resets to default values) the appropriate instance variables in the GridBagConstraints object. It then adds the component to its container, specifying the GridBagConstraints object as the second argument to the add method.

For instance, to make button 4 extra tall, the example has this code:

 c.ipady = 40; 

Note: The Java Tutorial's examples used to specify the constraints object differently. Rather than specifying the constraints with the add method, our examples used to invoke the setConstraints method on the GridBagLayout object, as shown here:

 GridBagLayout gridbag = new GridBagLayout(); pane.setLayout(gridbag); ... gridbag.setConstraints(button, c); pane.add(button); 

Before setting the constraints of the next component, the code resets the value of ipady to the default:

 c.ipady = 0; 

Table 8 shows all of the constraints for each component in GridBagLayoutDemo 's content pane. Values that aren't the default are in bold , values that are different from those in the previous table entry are in italics .

Table 8. Constraints for Components Handled by GridBagLayout

Component

Constraints

All components

 ipadx = 0  fill = GridBagConstraints.HORIZONTAL  

Button 1

 ipady = 0  weightx = 0.5  weighty = 0.0 gridwidth = 1 anchor = GridBagConstraints.CENTER insets = new Insets(0,0,0,0)  gridx = 0   gridy = 0  

Button 2

  weightx = 0.5   gridx = 1   gridy = 0  

Button 3

  weightx = 0.5   gridx = 2   gridy = 0  

Button 4

  ipady = 40   weightx = 0.0   gridwidth = 3   gridx = 0   gridy = 1  

Button 5

  ipady = 0  weightx = 0.0  weighty = 1.0   anchor = GridBagConstraints.SOUTH   insets = new Insets(10,0,0,0)   gridwidth = 2   gridx = 1   gridy = 2  

GridBagLayoutDemo has two components that span multiple columns ( buttons 4 and 5). To make button 4 tall, we gave it internal padding ( ipady ). To put space between buttons 4 and 5, we used Insets to add a minimum of 10 pixels above button 5, which we made hug the south edge of its cell.

All of the components in the pane container are as wide as possible, given the cells they occupy. The program accomplishes this by setting the GridBagConstraints fill instance variable to GridBagConstraints.HORIZONTAL , leaving it at that setting for all of the components. If the program didn't specify the fill, the buttons would be at their natural width, as shown in Figure 21.

Figure 21. The GridBagLayout application without the fill specified.

graphics/08fig24.gif

When you enlarge GridBagLayoutDemo 's window, the columns grow proportionately. This is because components in the first row, where each component is one column wide, have weightx = 1.0 . The actual value of the components' weightx is unimportant. What matters is that all components, and consequently all columns, have an equal weight greater than 0. If no components managed by GridBagLayout had weightx set, then, when their container was made wider, they would stay clumped together as in Figure 22.

Figure 22. None of the components in this example has weightx specified.

graphics/08fig25.gif

Note that, if you enlarge the window, the last row is the only one that gets taller. This is because only button 5 has weighty greater than 0.

The GridBagLayout API

Table 9 lists the constructors of the GridBagLayout and GridBagConstraints classes. Each of these classes has only one constructor, with no arguments. You can find the relevant API documentation online at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GridBagConstraints.html.

Table 9. GridBagConstraints and GridBagLayout Constructors

Constructor

Purpose

public GridBagConstraints()

Create an instance of GridBagConstraints . Instead of invoking methods on a GridBagConstraints object, you manipulate its instance variables, as described in Specifying Constraints (page 482).

public GridBagLayout()

Create an instance of GridBagLayout . Generally, the only method you might invoke on a GridBagLayout object is setConstraints , as demonstrated in the Note on page 486.

Examples That Use GridBagLayout

You can find examples of GridBagLayout throughout this book's examples. The following table lists a few.

Example

Where Described

Notes

GridBagLayoutDemo

This section

Uses many features ”weights, insets, internal padding, horizontal fill, exact cell positioning, multi-column cells, and anchoring (component positioning within a cell).

TextSamplerDemo

Using Text Components (page 60)

Aligns two pairs of labels and text fields, and adds a label across the full width of the container.

ContainerEventDemo

How to Write a Container Listener (page 658)

Positions five components within a container using weights, fill, and relative positioning.

 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net