Search

Dark theme | Light theme

October 24, 2011

Groovy Goodness: Customize Groovy Console Visual Output

The Groovy Console ($ groovyConsole) is a great tool to run Groovy scripts and experiment with Groovy. Normally when we run a script the return result (if not null) is shown as a string value. We can customize the way the value is shown by creating a new file with the name OutputTransforms.groovy in our GROOVY_HOME directory. Normally this directory is located in your user directory with the name .groovy.

In OutputTransforms.groovy we must fill the internal script variable transforms of type ArrayList with a closure where we do the actual customization of the return result. The closure has one parameter which is the return result of the script. We can check for example the type and then transform the result to a different output result.

The Groovy Console already contains some transformations for script results of type java.awt.Image, javax.swing.Icon and java.awt.Component with no parent. To see the customized visual output we must make sure we enable this in the View menu and select Visualize Script Results.

The following sample code show that we return a String result that starts with <html> and ends with </html> as a formatted JLabel. Other String values are prepended with the default text Groovy Console says:.

// File: ~/.groovy/OutputTransforms.groovy
import javax.swing.JLabel
import javax.swing.ImageIcion

transforms << { result ->
    if (result instanceof String) {
        if (result ==~ /<html>.*<\/html>/) {
            return new JLabel(result)
        } else if (result == 'mrhaki') {
            return new ImageIcon('/Users/mrhaki/Pictures/blog/haki-logo-black-64.png')
        } else {
            return "Groovy Console says: $result"
        }
    }
}