GridBagLayout Primer

A GridBagLayout is a layout manager included with all versions of Java. It lays out components into a notional grid of cells but components can span more than one cell in the layout. The number of cells in the layout is never explicitly specified, instead GridBagLayout works this out from the components in the layout. To specify how GridBagLayout places a given component, an instance of GridBagConstraints is associated with the component. The various constraints of the GridBagConstraints class are explained below.

anchor

If the component doesn't completely fill it's display area then the anchor constraint specifies how the component is positioned in the display area.

fill

The fill constraint how the component can be stretched to fill it's display area.

gridwidth and gridheight

These specify how many cells the component's height and width will occupy. A value of REMAINDER all remaining cells will be occupied. A value of RELATIVE means that all remaining cells except the last will be occupied. A component that uses RELATIVE for one of these constraints should theoretically be followed by a component that uses a value of REMAINDER for that same constraint.

gridx and gridy

These constraints specify the exact cell that a component is to occupy. If not specified explicity then these constraints should be left with the default value of RELATIVE.

ipadx and ipady

This constraint increases the components preferred height or width by the specified number of pixels.

insets

This constraints can increase the display area for the component. If any of the values used for insets is negative this has the effect of allowing the component to expand outside it's display area.

weightx and weighty

These constraints should be non-zero for the component to expand inside it's display area. They determine how the extra space in the layout is allocated once the preferred size's of the components are taken into account. If the weightx for a component is 5 and the total weights for it's row is 10 then the component will get half of any extra space available after allocating the preferred sizes for the row and will expand into it if it's fill constraint allows it. Note:These constraints are labelled as wgtx and wgty in GridBagger.