« Griffon <3's Java | Main | Taking Flight: A Year of Griffon »

Groovy Console Bling-Bling

Groovy 1.6 is about to hit the inter-webs, so I thought it was an appropriate time for me to emerge from a twitter induced blogging hiatus. But what to blog about? How about one of the funner items I added to the new release. AST Transformation have changed the way I think of annotations, the bind node in SwingBuilder has brought my GUIs closer to MVC nirvana, and Grapes have been a tasty experiment. But when it comes to plain old gratuitous fun, output visualizations in the Groovy Console will help you see your results in a new light.


Yes, you probably have seen something like this before, but it's such a neat Idea we had to copy re-implement it.

How does it work? Well, first and formost you have to turn it on. By default it is disabled, so it is less astonishing that way. It's in the menu in View->Visualize Script Results, and we remember what the last seting was when you exit as well. The built in transforms are fairly benign, if the script returns a java.awt.Image, a javax.swing.Icon, or a java.awt.Component that has no parent we display the object instead of the text. Everything else is still text. But that's not really interesting. It is also user extensible! If you have a file ~/.groovy/OutputTransforms.groovy the Groovy Console will insert an empty list named transforms, and you just need to add an appropriate closure into that variable and GroovyConsole will take the results and process those first.

The closure itself is fairly simple. The result of the script is passed in. If you want to transform it you return a non-null transformation. If you don't want to transform it you return null. And the output doesn't need to be a visual component either. You could make all numbers register as percentages:

transforms << { it -> if (it instanceof Number) "${it / 100}%" }

But visual results are much more fun. Here is a simple transform that will make all maps render in tables (it is also the transform that is displayed in this post):

transforms << {it ->
  if (it instanceof Map) {
    def jt = new javax.swing.JTable(
        it.collect{k, v->[k, v?.inspect()] as Object[]} as Object[][], 
        ['Key', 'Value'] as Object[])
    jt.preferredViewportSize = jt.preferredSize
    return new javax.swing.JScrollPane(jt)

Don't forget to have fun!


This page contains a single entry from the blog posted on February 17, 2009 9:17 PM.

The previous post in this blog was Griffon <3's Java.

The next post in this blog is Taking Flight: A Year of Griffon.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33