Harness the Power of Java's GridBagLayout
- Introducing GridBagLayout
- GridBagLayout Demonstration Application 1: Ten Dialog Box Scenarios
- Whats Next?
Also read Part 2, Laying Out Realistic GUIs the GridBagLayout Way.
GridBagLayout (one of Java’s original layout managers) has a bad reputation among Java developers. According to Ethan Nicholas’ "Reinventing GridBagLayout" blog entry, this layout manager is "ridiculously difficult to use." In a more extreme case, the author of a late 1990s Java book was loosely quoted as hating GridBagLayout. I hope that this series will improve GridBagLayout’s reputation.
I’ve divided this series into three articles. Part 1 (this article) introduces GridBagLayout, where you learn how to work with the java.awt.GridBagLayout and java.awt.GridBagConstraints classes. Part 2 uses GridBagLayout to lay out an address book GUI, which demonstrates this layout manager’s effectiveness in laying out realistic GUIs. In case you’re still not impressed with GridBagLayout, part 3 presents the JGoodies FormLayout alternative, and compares this layout manager with GridBagLayout so you can choose the layout manager that works best for you.
Introducing GridBagLayout
GridBagLayout consists of two classes: GridBagLayout and GridBagConstraints. GridBagLayout aligns components vertically and horizontally within a grid of rows and columns. Rows can have differing heights, and columns can have differing widths. GridBagLayout places components into cells—the intersections of rows and columns. A single component can occupy multiple cells; the region of cells that a component occupies is known as the component’s display area.
The grid’s orientation depends on the container’s ComponentOrientation—a property that encapsulates the language-sensitive orientation used to order the elements of a component or of text:
- For horizontal left-to-right orientations, grid coordinate (0,0) is in the upper-left corner of the container: x increases to the right and y increases downward.
- For horizontal right-to-left orientations, grid coordinate (0,0) is in the upper-right corner of the container: x increases to the left and y increases downward.
Before displaying a component, GridBagLayout considers the component’s minimum and preferred sizes when figuring out the component’s size. GridBagLayout also considers the component’s associated GridBagConstraints, which specifies where a component’s display area should be located on the grid, and how the component should be positioned within its display area. GridBagConstraints offers this information via the following constraints field variables:
- gridx and gridy identify the cell that contains the leading corner of the component’s display area: 0 values in these fields identify the cell at the grid’s origin. For horizontal left-to-right layout, the leading corner is the component’s upper-left corner; the leading corner is the component’s upper-right corner for horizontal right-to-left layout. The default value assigned to gridx and gridy is constant GridBagConstraints.RELATIVE, which indicates that a component is placed immediately after (along the x axis for gridx; along the y axis for gridy) the component previously added to the container.
- gridwidth and gridheight identify the number of cell columns and cell rows (respectively) in the component’s display area. The default value assigned to gridwidth and gridheight is 1. To indicate that the component’s display area ranges from gridx to the last cell in the row (gridwidth), or ranges from gridy to the last cell in the column (gridheight), assign constant GridBagConstraints.REMAINDER to the appropriate field. If you want to indicate that the component’s display area ranges from gridx to the next-to-last cell in its row (gridwidth), or ranges from gridy to the next-to-last cell in its column (gridheight), assign GridBagConstraints.RELATIVE to the appropriate field.
- fill determines whether (and how) to resize the component when its display area is greater than its requested size. The following GridBagConstraints constants are the possible values that can be assigned to this field:
- NONE tells GridBagLayout not to resize the component. This is the default.
- HORIZONTAL makes the component wide enough to fill its display area horizontally, without changing its height.
- VERTICAL makes the component tall enough to fill its display area vertically, without changing its width.
- BOTH makes the component completely fill its display area.
- ipadx and ipady identify the component’s internal padding—how much to add to the component’s minimum size—within the layout. The component’s width is at least ipadx*2 pixels because padding applies to both sides of the component. Similarly, the height is at least ipady*2 pixels. The default value assigned to both fields is 0.
- insets identifies the component’s external padding—the minimum amount of space between the component and the edges of its display area. The value assigned to this field is specified as a java.awt.Insets object. By default, null is assigned to this field—there is no external padding.
- anchor determines where to place a component within its display area when the component is smaller than that area. This field’s value is obtained from one of GridBagConstraints’ two sets of anchor constants. The older absolute constants correspond to the points on a compass: NORTH, SOUTH, WEST, EAST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST, and CENTER (the default). Unlike absolute anchor constants, which are not appropriate for localization, the relative anchor constants are interpreted relative to the container’s ComponentOrientation property: PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_START, and LAST_LINE_END.
- The following diagram illustrates how the relative anchor constants are interpreted in a container that has the default left-to-right component orientation.
------------------------------------------------- |FIRST_LINE_START PAGE_START FIRST_LINE_END| | | | | |LINE_START CENTER LINE_END| | | | | |LAST_LINE_START PAGE_END LAST_LINE_END| -------------------------------------------------
- weightx and weighty specify how to distribute space among columns (weightx) and rows (weighty), which is important for specifying resizing behavior. GridBagLayout calculates the weight of a column to be the maximum weightx of all the components in a column. If the resulting layout is smaller horizontally than the area it needs to fill, the extra space is distributed to each column in proportion to its weight. A column with a 0.0 weight receives no extra space. Similarly, a row’s weight is calculated to be the maximum weighty of all the components in a row. If the resulting layout is smaller vertically than the area it needs to fill, the extra space is distributed to each row in proportion to its weight. A row with a 0.0 weight receives no extra space.
Weights are positive real numbers ranging from 0.0 to (generally) 1.0: 0.0 is the default weight. When all components have 0.0 weights, they clump together in the container’s center.
GridBagLayout’s public GridBagLayout() constructor creates an instance of this class. After creating this object and establishing it as a container’s layout manager, one or more constraints objects are created by invoking the following GridBagConstraints constructors:
public GridBagConstraints() public GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady)
The former GridBagConstraints() constructor creates a GridBagConstraints object with constraints fields (such as public int gridx) set to default values. You must assign values to these fields explicitly via separate assignment statements. In contrast, you can assign values to all fields in one step via the second constructor.
Although a separate GridBagConstraints object can be created for each component being managed by the GridBagLayout class, the same object can be associated with multiple components. (Before you associate this object with a component, you usually modify various fields to specify appropriate layout details for the component.) A component and its constraints object then can be added to a container, often by invoking java.awt.Container’s public void add(Component comp, Object constraints) method:
JPanel panel = new JPanel (); panel.setLayout (new GridBagLayout ()); GridBagConstraints gbc = new GridBagConstraints (); // ... JButton button = new JButton ("Ok"); gbc.gridx = 1; gbc.gridy = 1; panel.add (button, gbc); button = new JButton ("Cancel"); gbc.gridx = 2; gbc.gridy = 1; panel.add (button, gbc); // ...
Behind the scenes (for J2SE 5.0, at least), the add(Component comp, Object constraints) method indirectly (and eventually) invokes the following GridBagLayout method to cache the component and its GridBagConstraints object in an internal hash table:
public void addLayoutComponent(Component comp, Object constraints)
The GridBagConstraints object is subsequently extracted from this hash table and used during a layout operation.
This method:
addLayoutComponent(Component comp, Object constraints)
invokes this GridBagLayout method to handle the caching:
public void setConstraints(Component comp, GridBagConstraints constraints)
Older application source code often explicitly invokes setConstraints() followed by Container’s public Component add(Component comp) method, which never invokes setConstraints(). In contrast to this older usage, I prefer the code fragment’s modern usage.
setConstraints(Component comp, GridBagConstraints constraints)