Skip to main content

Displaying messages in the system tray

Posted by mister__m on February 15, 2007 at 3:56 AM PST

Many folks are aware that Java SE 6 comes with the new SystemTray and TrayIcon classes that allows an icon to be added to the system tray - or status area or whatever it is called on your platform. One very cool feature that most articles/pieces don't mention is it is possible to display a message similar to the "Low battery" warning produced by laptops or the "Updates are ready to be installed" alert Windows Update displays so often.

Here is the code:

public class SysTray {
   public static void main(String[] args) throws Exception {
      TrayIcon icon = new TrayIcon(getImage(), "Java application as a tray icon",
            createPopupMenu());
      icon.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Hey, you activated me!");
         }
      });
      SystemTray.getSystemTray().add(icon);

      Thread.sleep(3000);

      icon.displayMessage("Attention", "Please click here",
            TrayIcon.MessageType.WARNING);
   }

   private static Image getImage() throws HeadlessException {
      Icon defaultIcon = MetalIconFactory.getTreeHardDriveIcon();
      Image img = new BufferedImage(defaultIcon.getIconWidth(),
            defaultIcon.getIconHeight(), BufferedImage.TYPE_4BYTE_ABGR);
      defaultIcon.paintIcon(new Panel(), img.getGraphics(), 0, 0);

      return img;
   }

   private static PopupMenu createPopupMenu() throws HeadlessException {
      PopupMenu menu = new PopupMenu();

      MenuItem exit = new MenuItem("Exit");
      exit.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            System.exit(0);
         }
      });
      menu.add(exit);

      return menu;
   }
}

When you run this sample, an hard-drive icon (borrowed from Swing's Metal L&F) will be displayed in the system tray. If you place the mouse over it for a few seconds, the "Java application as a tray icon" tooltip will be shown and right-clicking it will show a popup menu with a single option, Exit, that will terminate our sample.

The cool thing is that approximately 3 seconds after the icon appears, a warning message will pop up in your system tray - and if you are running Windows and hide the task bar, it will even become immediately visible. This feature can be quite useful for some scenario, such as monitoring applications.

There are several other hidden gems in Java SE 6. Let's keep on searching for them...

Related Topics >>