2007-12-15

Two Hello World Windows in Groovy

Groovy is scripting language on the Java platform. Groovy is interesting because it can be compiled into Java byte-code and makes heavy use of closures.

Groovy Hello World

In the beginning, I ported my Jython version into Groovy. It looks pretty much the same as the Jython version:

// Hello World in Groovy
f = new javax.swing.JFrame("Hello World")
f.setSize(170,70)
f.contentPane.layout = new java.awt.FlowLayout()
f.defaultCloseOperation = javax.swing.JFrame.EXIT_ON_CLOSE
f.add(new javax.swing.JLabel("Label me:"))
f.add(new javax.swing.JButton("Press me"))
f.show()

Groovy + SwingBuilder Hello World

Groovy has a helper class called SwingBuilder to make it much easier to write Swing applications. Here's one way to re-write the program:

// Hello World Window in Groovy + SwingBuilder
sb = new groovy.swing.SwingBuilder()
f = sb.frame(
  title:"Hello World"
  ,size:[170,70]
  ,defaultCloseOperation: javax.swing.JFrame.EXIT_ON_CLOSE) {
  flowLayout()
  label(text:"Label me:")
  button(text:"Press me")
}
f.show()

SwingBuilder is quite wonderful because it allows you to define a GUI with a minimum of code noise. The definition of a JFrame probably maps a keyword X to a setX() function but I haven't worked out how SwingBuilder converts words such as flowLayout(), label and button to Swing objects and functions.

No comments:

Post a Comment