Info on GridBagLayouts


This page outlines the padding and resizing constraints in GridBag Layout for Java.

If you don't include any padding constraints, all your components will clump together in the centre of your interface. In addition, you usually need to include resizing constraints so that when you resize your interface (or a user resizes a web browser if you're making an applet) the components don't drop off the edge of the interface.

The following lists the constraints for dealing with padding and resizing...

GridBagConstraints.insets
The number of pixels between an object and the cell it is in. This should be set equal to a java.awt.Insets object. The easiest way to do this is...

c.insets = new Insets(top, left, bottom, right);

Where "top" is replaced by the pixels you want between the component and the top of its cell, and similarly for the others.

GridBagConstraints.ipadx, GridBagConstraints.ipady
These add a set of invisible pixels to the width/height of the component. For example, if you set the c.ipadx = 2 with component added will act as if it's 4 pixels wider in total, though it will look the same width.

GridBagConstraints.fill
If the interface is larger than the components, you can set components to fill up the extra space. They will expand to fill in the gaps. You can set this to GridBagConstraints.NONE/VERTICAL/HORIZONTAL/BOTH depending on which way you want the components to expand.

GridBagConstraints.anchor
This determines to alignment of the component in its cell. It can be set to:
GridBagConstraints.SOUTH/SOUTHWEST/WEST/ NORTHWEST/NORTH/NORTHEAST/EAST/SOUTHEAST.

GridBagConstraints.weightx, GridBagConstraints.weighty
These determine the importance of the components in resizing. The best thing to do is set one component with weightx and weigthy = 1 and the rest = 0. Usually this will suffice.


Note that you don't have to explicitly set all these constraints each time for each component, you just need to change the constraints you want each cell to vary by. A typical sequence might look like...

// General constraints.
c.insets = new Insets(20, 10, 20, 10);
c.ipadx = 1;
c.ipady = 1;
c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = 1;
c.gridheight = 1;
 
// Component 1.
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
gridBag.setConstraints(myComponent1, c);
add(myComponent1);
 
// Component 2.
c.gridx = 1;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.SOUTHEAST;
gridBag.setConstraints(myComponent2, c);
add(myComponent2);
 
// Component 3.
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.anchor = GridBagConstraints.SOUTHWEST;
gridBag.setConstraints(myComponent3, c);
add(myComponent3);

Which should give something like...

12
3