Java Reference
In-Depth Information
constraints:BL.CENTER)
}
}
The
edt
method on
SwingBuilder
builds a GUI using the event dispatch thread. It
takes a closure as an argument, and this is where the fun starts. The first statement inside
the closure is a call to the
frame
method, but the fact is, there's no frame method in
SwingBuilder
. The builder's metaclass intercepts that call (via
methodMissing
)
andinterprets it as arequest toinstantiate the
javax.swing.JFrame
class. The
frame
method here lists a series of map entries, which are intended to supply values for the
title, visibility, and close operation on the
JFrame
. The builder interprets them as calls to
setTitle
,
setVisible
, and
setDefaultCloseOperation
on the
JFrame
in-
stance.
After the parentheses there's another closure. That's interpreted to mean I'm about to sup-
ply components that will be added to the
JFrame
instance. The next call is to the
label
method, which of course doesn't exist. The Swing builder knows to generate a
JLabel
instance as a result, call its
setIcon
method with a new
ImageIcon
holding the image
returned by Google Chart, and place the
JLabel
in the center of a
BorderLayout
.
Finally, after the frame closure I invoke the
pack
method on
JFrame
to make the result-
ing GUI just big enough to hold the image. The next listing contains the complete script
(without the asserts, just to keep the listing short).
Listing 2.1. Building a Swing UI 3D pie chart using Google Chart
import java.awt.BorderLayout as BL
import javax.swing.WindowConstants as WC
import groovy.swing.SwingBuilder
import javax.swing.ImageIcon
def base = 'http://chart.apis.google.com/chart?'
def params = [cht:'p3',chs:'250x100',
chd:'t:60,40',chl:'Hello|World']
String qs = params.collect { k,v -> "$k=$v" }.join('&')
SwingBuilder.edt {
frame(title:'Hello, Chart!', pack: true,
visible:true, defaultCloseOperation:WC.EXIT_ON_CLOSE) {
label(icon:new ImageIcon("$base$qs".toURL()),