An easy to use GridBagConstraintsBuilder (using Fluent API and Java 5)


The number of times i needed to write a GUI using Java Swing can almost be counted with one single finger (no not that finger). Like most Java developers i dislike it. I have always been more a Web front-end and server side developer.

Swing (Ugh ...)

I guess one issue with Swing is its API, that really sucks. It also did not get a Java 5 makeover (perhaps Java 7) . So JSF/Swing really smells like Milli Vanilli and Paula Abdul. There has hardly been any innovative development since they stormed the top charts. I really believe they could have made the API a lot easier to use. As far as I can see the Swing API is really made to be used by GUI building tools. The whole Java Bean specification with its properties/events was intended for the property inspectors/sheets in GUI builders (even the JavaDoc sometimes mentions that). So if that is truly the case, then why didn't Java specified a portable format to store the GUI design in (as opposed to using code statements). We all know Borland influenced this RAD part of Java (Delphi at the time was very popular), Delphi did have a special file to store the GUI design in.

Anyway because there is no portable format, we often find ourselves developing the GUI programmatic. That's what i had to do this weekend (to build a demo for JBoss Cache)

The API of the GridBagLayout

I needed the GridBagLayout a lot so found myself using the class which is in one of the darkest areas of the Java API «insert thunder and two lightning flashes here». It uses public fields! Which if it was really only a data carrier would be ok, but the values they accept are often bound. The gridwidth should be non-negative. Other properties may only have one of a defined set of predefined values (e.g, fill has as possible values NONE, HORIZONTAL etc).

Then there is the constructor. Constructor arguments should include only parameters for the information required for the object to exist. In the case of the GridBagConstraints they took the all-or-nothing approach. This makes it terrible to use. No configuration by exception and the ability to use the "default values" the JavaDoc speaks off. Here is an example:

GridBagConstraints gbc = new GridBagConstraints(2, 4, 3, 2, 1.0,
                      1.0,0, 0, new Insets(2,2,2,2), 0, 0);

Now from left to right and by heart, name the semantics of each argument.... (eahh...time is up).

Let's improve it

So i decided to make an easy to use GridBagConstraintsBuilder using the Fluent API Design and take more out of Java 5 (in this case enums)., 0).build();, 0).insetsAll(3)

The source code (Maven project) for this small API can be downloaded here ( i guess it is not perfect, but really made my weekend a lot better!)

This article does not necessarily reflect the technical opinion of EDC4IT, but purely of the writer. If you want to discuss about this content, please send us an email at