Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 160 ]

})
}
scrollPane (constraints:BorderLayout.SOUTH){
results = table() {
tableModel(list:[]) {
propertyColumn(header:'Sender',
propertyName:'from',preferredWidth:20)
propertyColumn(header:'Tweet',
propertyName:'tweet',preferredWidth:140)
}
}
}
}
}
frame.pack()
frame.show()

The GroovyMarkup that we use for SwingBuilder is pretty much identical to what
we've seen before, with a few differences. Unlike MarkupBuilder and NodeBuilder,
we can't simply invent tags to insert into GroovyMarkup, as this would not make
sense. The tags must correspond to real UI widgets or controls that can be placed
into the UI. In the preceding code, we use frame, menuBar, panel, and textField,
among others. There are other non-widget tags, such as tableModel, that must be
used in conjunction with a table tag and others.


In the preceding example, we start with a frame tag. The SwingBuilder class takes
care of creating a JFrame widget for this frame, and maintaining it. Any further
widgets declared in the nested closure later in this frame will be added to the frame.
Take the preceding scrollPane, for example. Widgets that are nested below this will
be added to the scrollPane, and so on. The nesting of the closure code that we use
to declare the components dovetails exactly with how these components are nested
in the UI. Declaring a widget returns the corresponding Swing widget; so the frame
variable in the preceding code contains a JFrame instance that allows us to call the
regular swing pack() and show() methods to display the UI.


SwingBuilder handles the Swing event loop and dispatches any event that occurs.
All we need to do is supply a closure for the actionPerformed attribute of any
widget that we want to provide event handling for. This is far neater than the
anonymous classes that regular Swing code is usually littered with.


http://www.ebook3000.com
Free download pdf