More desktop integration: the system tray
The API consists of 2 classes:
java.awt.SystemTray and java.awt.TrayIcon.The programmer cannot instantiate
SystemTray but instead it has to ask for it: SystemTray.getSystemTray(). The system tray si not supported on all platforms so before trying to access and use it, its availability shall be checked: SystemTray.isSupported().On the other hand the
TrayIcon class can be instantiated as many times as needed - more than one icon can be added to the system tray from an application. The icon is obviously not just a simple image. It supports mouse events and a pop-up menu. It also allows the application to display messages to the user during its progress. But enough with the theory, let’s see how it works.
package com.littletutorials.systray;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SysTrayDemo
{
protected static TrayIcon trayIcon;
private static PopupMenu createTrayMenu()
{
ActionListener exitListener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Bye from the tray");
System.exit(0);
}
};
ActionListener executeListener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "Nothing here, press the button!",
"User action", JOptionPane.INFORMATION_MESSAGE);
trayIcon.displayMessage("Done", "Bravo!", TrayIcon.MessageType.INFO);
}
};
PopupMenu menu = new PopupMenu();
MenuItem execItem = new MenuItem("Execute...");
execItem.addActionListener(executeListener);
menu.add(execItem);
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(exitListener);
menu.add(exitItem);
return menu;
}
private static TrayIcon createTrayIcon()
{
Image image = Toolkit.getDefaultToolkit().getImage("ds.jpg");
PopupMenu popup = createTrayMenu();
TrayIcon ti = new TrayIcon(image, "Java System Tray Demo", popup);
ti.setImageAutoSize(true);
return ti;
}
public static void main(String[] args)
{
if (! SystemTray.isSupported())
{
System.out.println("System tray not supported on this platform");
System.exit(1);
}
try
{
SystemTray sysTray = SystemTray.getSystemTray();
trayIcon = createTrayIcon();
sysTray.add(trayIcon);
trayIcon.displayMessage("Ready",
"Tray icon started and tready", TrayIcon.MessageType.INFO);
}
catch (AWTException e)
{
System.out.println("Unable to add icon to the system tray");
System.exit(1);
}
}
}












Leave a Reply