You are on page 1of 9

How to Use GridBagLayout http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.

html#gridbagConstrai nts Note: This lesson covers writing layout code by hand, which can be challenging. If you are not interested in learning all the details of layout management, you might prefer to use the GroupLayout layout manager combined with a builder tool to lay out your GUI. One such builder tool is the NetBeans IDE. Otherwise, if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager. Here is a picture of an example that uses GridBagLayout.

Click the Launch button to run GridBagLayoutDemo using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.

The code for GridBagDemo is in GridBagLayoutDemo.java. is one of the most flexible — and complex — layout managers 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.
GridBagLayout

The following figure shows the grid for the preceding applet. 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.

... //For each component to be added to this container: //.Set instance variables in the GridBagConstraints instance. This behavior is also specified by the program. You will also notice that each component takes up all the available horizontal space — but not (as you can see with button 5) all the available vertical space.Create the component. as demonstrated in the next sections. gets all the new vertical space. JPanel pane = new JPanel(new GridBagLayout()). //. Specifying Constraints The following code is typical of what goes in a container that uses a GridBagLayout.. you will notice that the bottom row.. GridBagConstraints c = new GridBagConstraints(). which contains Button 5.. passing it a GridBagConstraints object. The way the program specifies the size and position characteristics of its components is by specifying constraints for each component. c).. The new horizontal space is split evenly among all the columns. The following sections explain the constraints you can set and provide examples. You will see a more detailed example in the next section.. pane.add(theComponent. The preferred approach to set constraints on a component is to use the Container. This resizing behavior is based on weights the program assigns to individual components in the GridBagLayout.add variant.If you enlarge the window as shown in the following figure..

REMAINDER. it is possible to reuse the same GridBagConstraints instance for multiple components. Use GridBagConstraints. gridheight Specify the number of columns (for gridwidth) or rows (for gridheight) in the component's display area. but do not change its height). We recommend specifying the gridwidth and gridheight values for each component rather than just using GridBagConstraints.RELATIVE to specify that the component be the next to last one in its row (for gridwidth) or column (for gridheight). VERTICAL (make the component tall enough to fill its display area vertically. not the number of pixels it uses. The leftmost column has address gridx=0 and the top row has address gridy=0. Use GridBagConstraints. this tends to result in more predictable layouts. gridy Specify the row and column at the upper left of the component.RELATIVE and GridBagConstraints.RELATIVE. and BOTH (make the component fill its display area entirely).REMAINDER to specify that the component be the last one in its row (for gridwidth) or column (for gridheight). However. fill Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component. Note: The following discussion assumes that the GridBagLayout controls a container that has a left-to-right component orientation. it is recommended that you do not reuse GridBagConstraints. Use GridBagConstraints. gridwidth. Valid values (defined as GridBagConstraints constants) include NONE (the default). We recommend specifying the gridx and gridy values for each component rather than just using GridBagConstraints. but do not change its width). These constraints specify the number of cells the component uses. The default value is 1.As you might have guessed from the above example. You can set the following GridBagConstraints instance variables: gridx. as this can very easily lead to you introducing subtle bugs if you forget to reset the fields for each new instance. this tends to result in more predictable layouts. HORIZONTAL (make the component wide enough to fill its display area horizontally. even if the components have different constraints. Note: GridBagLayout does not allow components to span multiple rows unless the component is in the leftmost column or you have specified positive gridx and gridy values for the component.RELATIVE (the default value) 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 component was added. .

0 and 1. This is because when the weight is 0. weightx. the GridBagLayout puts any extra space between its grid of cells and the edges of the container. the height of the component will be at least its minimum height plus ipady*2 pixels. instead. since they enable easier localization. For example. The width of the component will be at least its minimum width plus ipadx*2 pixels. FIRST_LINE_START. FIRST_LINE_END.4. The default value is zero. Unless you specify at least one non-zero value for weightx or weighty.the minimum amount of space between the component and the edges of its display area. We recommend that you use the new constants. since the padding applies to both sides of the component. By default. LINE_END. PAGE_START. ------------------------------------------------|FIRST_LINE_START PAGE_START FIRST_LINE_END| | | | | |LINE_START CENTER LINE_END| | | | | |LAST_LINE_START PAGE_END LAST_LINE_END| ------------------------------------------------- Version note: The PAGE_* and *LINE_* constants were introduced in 1. Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty). Larger numbers indicate that the component's row . Similarly. weighty Specifying weights is an art that can have a significant impact on the appearance of the components a GridBagLayout controls. LINE_START. The value is specified as an Insets object.0 as the extremes: the numbers in between are used as necessary. LAST_LINE_END. ipady Specifies the internal padding: how much to add to the size of the component. and LAST_LINE_START.ipadx. anchor Used when the component is smaller than its display area to determine where (within the area) to place the component.0 (the default). this is important for specifying resizing behavior. left-to-right component orientation. each component has no external padding. NORTHEAST indicates the top-right part of the display area. insets Specifies the external padding of the component -. Previous releases require values named after points of the compass. Generally weights are specified with 0. all the components clump together in the center of their container. Here is a picture of how these values are interpreted in a container that has the default. Valid values (defined as GridBagConstraints constants) are CENTER (the default). PAGE_END.

fill = GridBagConstraints. pane.5. is a picture of the GridBagLayoutDemo application. each row's weight is related to the highest weighty specified for a component within that row.java. c.gridy = 0.HORIZONTAL. consult the example index.HORIZONTAL.gridx = 0. the weight is related to the highest weightx specified for a component within that column. if (shouldFill) { //natural height. The following code creates the GridBagLayout and the components it manages. . } button = new JButton("Button 1"). Alternatively. c. You can find the entire source file in GridBagLayoutDemo. pane.fill = GridBagConstraints. if (shouldWeightX) { c.setLayout(new GridBagLayout()). again.add(button.or column should get more space. Click the Launch button to run GridBagLayoutDemo using Java™ Web Start (download JDK 6). Similarly. } c. The Example Explained Here. For each column. in the context of explaining how the example program works. button = new JButton("Button 2"). to compile and run the example yourself.5. maximum width c. The next section discusses constraints in depth. JButton button.HORIZONTAL. c). GridBagConstraints c = new GridBagConstraints(). c.weightx = 0. with each multicolumn component's weight being split somehow between the columns the component is in. c. Extra space tends to go toward the rightmost column and bottom row.weightx = 0.fill = GridBagConstraints.

ipady = 0. It then adds the component to its container. the example has this code: c.HORIZONTAL.gridy = 1. c.add(button.gridx = 0. at the start of the first line.fill = GridBagConstraints. c. c). or relative to the component's baseline. c.0. however in real-life situations it is recommended that you do not reuse GridBagConstraints. pane. c). including baseline-relative values. For example. c. This example uses one GridBagConstraints instance for all the components the GridBagLayout manages.ipady = 40.anchor = GridBagConstraints. and so on). c. c. //make this component tall c. to make button 4 be extra tall.c. the code sets (or resets to default values) the appropriate instance variables in the GridBagConstraints object. the code resets the value of ipady to the default: c. c.5. south.gridy = 0. c. then you can specify whereabouts in the display area the component will be displayed by using the GridBagConstraints. c. c. //2 columns wide c.add(button.see .weighty = 1.gridy = 0. specifying the GridBagConstraints object as the second argument to the add method.0. east. If a component's display area is larger than the component itself. c. pane. //aligned with button 2 c.ipady = 40.gridx = 1.gridx = 2. //request any extra vertical space c. button = new JButton("Long-Named Button 4"). c. //top padding c.gridx = 1. Just before each component is added to the container.HORIZONTAL.ipady = 0.0).0.gridwidth = 3.fill = GridBagConstraints. //third row pane. The anchor constraint's values can be absolute (north.PAGE_END. button = new JButton("Button 3"). //bottom of space c.insets = new Insets(10. c). and so on). or orientation-relative (at start of page. button = new JButton("5").gridy = 2.HORIZONTAL. And before setting the constraints of the next component. For a full list of the possible values of the anchor constraint.weightx = 0.gridwidth = 2.fill = GridBagConstraints. as this can very easily lead to you introducing subtle bugs if you forget to reset the fields for each new instance. pane.add(button.anchor constraint. at end of line. c).weightx = 0.0. //reset to default c.add(button. west.

which you might see in other programs as well. c). we recommend you use the Container. Rather than specifying the constraints with the add method.0 weighty = 1.0 anchor = GridBagConstraints.5 gridx = 2 gridy = 0 ipady = 40 weightx = 0. For example: GridBagLayout gridbag = new GridBagLayout(). pane. .the API documentation for GridBagConstraints.PAGE_END.add(button). Note: The Tutorial's examples used to specify the constraints object a different way.0 gridwidth = 1 anchor = GridBagConstraints..0.0 gridwidth = 3 gridx = 0 gridy = 1 ipady = 0 weightx = 0.0) gridx = 0 gridy = 0 weightx = 0.anchor. Values that are different from those in the previous table entry are marked in italics.add method code than if you were to use setConstraints.PAGE_END insets = new Insets(10. However. Component Constraints All components ipadx = 0 fill = GridBagConstraints. since it makes for cleaner Here is a table that shows all the constraints for each component in GridBagLayoutDemo's content pane. Values that are not the default are marked in boldface.0.CENTER insets = new Insets(0.HORIZONTAL ipady = 0 weightx = 0.0. You can see in the code extract above that Button 5 specifies that it should be displayed at the end of the display area by setting an anchor at GridBagConstraints.0) gridwidth = 2 Button 1 Button 2 Button 3 Button 4 Button 5 .setConstraints(button. gridbag.. pane. our examples used to invoke the setConstraints method on the GridBagLayout object.5 gridx = 1 gridy = 0 weightx = 0.setLayout(gridbag).5 weighty = 0.0.

The actual value of these components' weightx is unimportant. The program accomplishes this by setting the GridBagConstraints fill instance variable to GridBagConstraints. If the program did not specify the fill. and consequently.5. then any space is distributed according to the GridBagContainer weights.HORIZONTAL. the components would stay clumped together in the center of the container. All the components in the pane container are as wide as possible. the last row is the only one that gets taller. all the columns. have an equal weight that is greater than 0. like this: When you enlarge GridBagLayoutDemo's window. and we made button 5 hug the bottom edge of its cell. we used insets to add a minimum of 10 pixels above button 5. To make button 4 tall. the buttons would be at their natural width.gridx = 1 gridy = 2 GridBagLayoutDemo has two components that span multiple columns (buttons 4 and 5). leaving it at that setting for all the components. This is because only button 5 has weighty greater than zero. What matters is that all the components. where each component is one column wide. If no component managed by the GridBagLayout had weightx set. Note that if you enlarge the window. we added internal padding (ipady) to it. has weightx = 0. To put space between buttons 4 and 5. given the cells that they occupy. This is because each component in the first row. the columns grow proportionately. . like this: If the container is given a size that is smaller or bigger than the prefered size. then when the components' container was made wider.

multi-column cells. and relative positioning. fill. Listener . Instead of invoking methods on a GridBagConstraints object. and anchoring (component positioning within a cell). horizontal fill. Container using weights. Generally. you manipulate its instance variables. insets. with no arguments. internal padding. Where Notes Example Described GridBagLayoutDemo This section Uses many features — weights. exact cell positioning. as demonstrated in The Example Explained. The following table lists a few.The GridBagLayout API The GridBagLayout and GridBagConstraints classes each have only one constructor. ContainerEventDemo How to Write a Positions five components within a container. the only method you invoke on a GridBagLayout object is setConstraints. TextSamplerDemo Using Text Aligns two pairs of labels and text fields. as described in Specifying Constraints. plus Components adds a label across the full width of the container. Examples that Use GridBagLayout You can find examples of using GridBagLayout throughout this tutorial.