Let's go forward a couple of weeks after that, Eitan and I were discussing how to plug in UI views with Groovy into JMatter (two small samples here and here) when he had the brilliant idea of adding css support to SwingBuilder. At that time SwingBuilder was "too monolithic", meaning that making css+swing+groovy would require a whole subclass and some DRY no-nos.
Fast forward to the latest RC releases of Groovy 1.1 and turns out that marrying css+swing+groovy is just a couple of lines away, no need to subclass the builder! Thanks to some clever extension points available in SwingBuilder's parent (FactoryBuilderSupport) it is possible to register an attributeDelegate, a
Closure
, that will take care of any css related attributes and wire it as they should. Let's see a trivial example, first a screenshot showing two labels, the first one without css settings, the second with css settings; notice the frame has a white background
Now let's look at the css rules, which are very simple
And finally let's have a look at the code that makes this possible
Though the code is simple a small explanation of what is going on is in order
- Before showing the UI (actually creating any Swing component), the CSSEngine must be initialized, by default looks for a file named styles.css in the classpath (please have a look at JMatter's manual for more info on the subject).
- The static
build()
method will create a Swing hierarchy inside the EDT while assigning a SwingBuilder as delegate of the building closure. - The css attributeDelegate is then added to that particular SwingBuilder instance.
- AttributeDelegates receive priority in reverse order they way registered, as the css attributeDelegate is the last one, it will be the first to process a node's attributes.
- The css attributeDelegate removes an attribute named 'cssClass' and if not null then assumes it must be a css class for the current node.
With Css4Swing, Fuse, Substance, the teachings from the FilthyRich masters and Groovy there is no excuse to make your Swing apps look outdated and ugly.
Keep on Groovying!