Friday, January 19, 2007

Groovy and SwingBuilder

In my comparison of IronPython, Groovy and JRuby I used a "naked" Swing API to create a GUI application using Groovy. Groovy comes with a nice library called SwingBuilder that simplifies a lot of work with Swing. I couldn't find any documentation for SwingBuilder but the source code is pretty straight-forward. In my opinion, the best thing in the SwingBuilder version is the way you declare that a form has a button:

def frame = swing.frame(defaultCloseOperation: WC.EXIT_ON_CLOSE) {
button('OK', actionPerformed: click)

You can pass a closure to the frame method.
I really like this way. It allows you to create your GUI in a more declarative way.

As was suggested by Martin C. Martin and Dierk Koenig (many thanks!) on the Groovy-user list, the code might look something like the following:

import javax.swing.WindowConstants as WC

click = { event ->
event.source.text = "Pressed!"

def swing = new groovy.swing.SwingBuilder()
def frame = swing.frame(
size: [200, 200],
defaultCloseOperation: WC.EXIT_ON_CLOSE,
title: 'Hello' ) {
button('OK', actionPerformed: click)

No comments: