Support Forums

Full Version: Teaching how to use the System Tray in Java!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Learning how to use this exciting API is quite easy. So first lets start.

To make this work, we need to import a couple packages,
Code:
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
This imports the Java AWT package so we can use the API.

We need to figure out if the OS supports the System tray feature in Java, to do so, we add this if-statement,
Code:
if (SystemTray.isSupported()) {
}
The isSupported() method returns a boolean whether or not this feature is supported by the OS. Everything in this tutorial will be put into this statement that has to do with constructing our system tray function.

Next up, we are going to implement the SystemTray class as a constructor. Its as shown,
Code:
SystemTray tray = SystemTray.getSystemTray();

Now we can get started on working on the actual function.

Here, we get the image we want as our icon,
Code:
Image image = Toolkit.getDefaultToolkit().getImage("image.gif");
As you can see, it uses the image specified in the file to be used as the tray icon.

Fnally we add the second last part, adding the actual icon to the tray.
Code:
TrayIcon trayIcon = new TrayIcon(image, "Your application is now running...");
Pretty straight forward here.

And we must add it enclosed in a try/catch statement as follows,
Code:
try {
                tray.add(trayIcon); // add our icon to the tray
            } catch (AWTException e) {
                // output the error
            }

That was all added in the if statement, so it should all look like,
Code:
if (SystemTray.isSupported()) {
            SystemTray tray = SystemTray.getSystemTray();
            Image image = Toolkit.getDefaultToolkit().getImage("gifIcon.gif");
            TrayIcon trayIcon = new TrayIcon(image, "Your application is now running...");

            try {
                tray.add(trayIcon); // add our icon to the tray
            } catch (AWTException e) {
                // output the error
            }
}

Congratulations, your finished! That wasnt so hard now was it. Theres also many other cool things you can do with this API, find more information here,
http://java.sun.com/javase/6/docs/api/ja...yIcon.html

I have provided you with a cool little application that shows the different uses assosciated with events using the System Tray API. Download it here, (includes src)
http://uppit.com/v/4SGZNWS9

Enjoy!
~ Anthony