Tuesday, 16 January 2007

Groovy in System Tray

As of Java 1.6 there is a cool feature available - System Tray. Actually, System Trasy plus nice notifications which look like a balloon on Windows. Now you can put Duke next to your favorite icons, if you like!

An example source code is available on the java docs page. Indeed, it is an example and even not a fully working one. I am not going to rewrite it - I believe Sun it works. Instead, I will try making the code more ... groovy ;-)

Here it is, System Tray example in Groovy:

import java.awt.Image
import java.awt.AWTException
import java.awt.MenuItem
import java.awt.PopupMenu
import java.awt.SystemTray
import java.awt.Toolkit
import java.awt.TrayIcon

def trayIcon = null

def exit = { e ->
println "Exiting ..."

def showMessage = { e ->
trayIcon.displayMessage("Action Event",
"An Action Event Has Been Peformed!",

if (SystemTray.isSupported()) {
def tray = SystemTray.getSystemTray()

def image = Toolkit.getDefaultToolkit().

def popup = new PopupMenu()
popup.add(new MenuItem(label:"Exit", actionPerformed:exit))

trayIcon = new TrayIcon(image:image, tooltip:"Tray Demo",
popup:popup, imageAutoSize:true,
try {
} catch (AWTException e) {
println e
} else {
prinltn "System Tray not supported"

As you can see it is possible to make Duke shout: Groovy did it! However, the code looks more like java. And what is worse, I am afraid we can't make it more groovy, using Swing Builder (the popup menu could be 'built'). The Tray functionality sits under java.awt package, which the Swing Builder does not support I think (well, it did not work for me). Luckily, we can still use Groovy's closures instead of Action Listeners.

Nevertheless, it works fine and - what is worth stressing here - it is platform independent! I have run the example successfully on GNOME, KDE and Win Xp desktops. Here are my screenshots:



Windows Xp

And two Dukes, if you would like to run the example on your desktop

Oh, and one more thing. If you are curious what other dynamic languages support System Tray, my friend, Andrzej, shows how to do this in Iron Python. See his article here.


Anonymous said...

This is great. I am just now getting into Groovy, coming from a Java/C# background. Are you still using it?

I noticed you haven't updated in a while.

Maggie said...

Keep up the good work.

Anonymous said...

generic propecia propecia lawsuit new jersey - generic propecia in australia