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 it dislike it. Why, do so many of us dislike it? I have always been more a server side developer (CORBA, EJB, Web Services etc). I did allow Servlets/JSP/JSF into my circle though, that’s a lot of “fun”.

I guess one issue with Swing is its API, that really sucks. It also did not get a Java 5 makeover (perhaps Java 7) . 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 why did’t Java then 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)

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 flashed 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 valuesNONE, 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 hearth, name the semantics of each argument…. (eahh…time is up).

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).

1
2
GridBagConstraintsBuilder.at(0, 0).build();
GridBagConstraintsBuilder.at(0, 0).insetsAll(3).absoluteAnchor(AbsoluteAnchor.WEST).build();

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

  • Share/Bookmark

About this entry