To wrap up our overview of AST transformations, let's finish by speaking about two transformations very useful to Swing developers: @Bindable and @Vetoable. When creating Swing UIs, you're often interested in monitoring the changes of value of certain UI elements. For this purpose, the usual approach is to use JavaBeans PropertyChangeListeners to be notified when the value of a class field changes. You then end up writing this very common boiler-plate code in your Java beans:
Fortunately, with Groovy and the @Bindable annotation, this code can be greatly simplified:
Now pair that with Groovy's Swing builder new bind() method, define a text field and bind its value to a property of your data model:
The binding also works with simple expressions in the closure, for instance something like this is possible too:
You may also be interested in having a look at ObservableMap and ObservableList, for a similar mechanism on maps and lists.
Along with @Bindable, there's also a @Vetoable transformation for when you need to be able to veto some property change. Let's consider a Trompetist class, where the performer's name is not allowed to contain the letter 'z':
Looking at a more thorough Swing builder example with binding:
Running this script shows up a frame with a text field and a lable below, and the label's text is bound on the text field's content.
SwingBuilder has evolved so nicely in the past year that the Groovy Swing team decided to launch a new project based on it, and on the Grails foundations: project Griffon was born. Griffon proposes to bring the Convention over Configuration paradigm of Grails, as well as all its project structure, plugin system, gant scripting capabilities, etc.
If you are developing Swing rich clients, make sure to have a look at Griffon.