Taming the GridBagLayout
Of the standard layout managers of the Java SDK, the GridBagLayout
is the most useful one, but its complexity has also been known to strike
fear in the hearts of programmers. Part of the complexity lies in
of setting up the grid bag constraints.
Consider for example the program in http://java.sun.com/docs/books/tutorial/uiswing/events/example-swing/ContainerEventDemo.java.
(To run the program, click here
[with a Java 2 enabled browser, of course]).
Can you figure out from the init() method why the grid bag
result in the given layout?
There are two problems with this code.
Some programmers make a new GridBagConstraints object for
and populate it with the non-default settings. That's easier to read,
the code is quite bloated. Here
is a typical example.
- The RELATIVE/REMAINDER approach is confusing. Using gridx/gridy/gridwidth/gridheight
is easier to understand, particularly if you are familiar with HTML
- The code uses a single GridBagConstraints object,
and unsetting various values. It is confusing to keep track of the
For example, was it really intended that the buttons are stretched
or did the programmer just forget to turn off the BOTH
the fill constraint?
What the world needs is a more convenient method of setting the grid
constraints. I developed a convenience class GBC that solves
problem. Here is a usage example that produces the same layout as the
from the Java tutorial:
As you can see, the component positions and the various constraints are
to spot. (Keep in mind that the grid bag coordinates are x/y values and
new GBC(0, 0)
new GBC(0, 1)
new GBC(0, 2)
new GBC(1, 2)
new GBC(0, 3)
The GBC helper class uses two tricks:
None of this is rocket science, but I think it is a clean and useful
that should make the GridBagLayout less scary.
- It extends the GridBagConstraints class. Therefore, you can
the GBC object to the add call. And you can use GBC
instead of GridBagConstraints as a prefix for those pesky
- The various set methods return the this
so that they can be conveniently chained.