Create Tray Icon

The system tray is an area of the desktop where users can access running programs. This area may be referred to differently on various operating systems.

On Windows, the system tray is referred to as the Taskbar Status Area, while on the GNU Network Object Model Environment (GNOME) Desktop it is referred to as the Notification Area. On K Desktop Environment (KDE) this area is referred to as the System Tray.

However, on each system the tray area is shared by all applications running on the desktop.

The TrayIcon class functionality goes beyond the icon that is displayed in the tray. It also includes a text tooltip, a pop-up menu, ballon messages, and a set of listeners associated with it.

A TrayIcon object generates various mouse events and supports the addition of corresponding listeners to receive notification of these events. The TrayIcon class processes some of the events itself. For example, by default, when a right-click is performed on the tray icon, it displays the specified pop-up menu. When a double-click is performed, the TrayIcon object generates an ActionEvent to launch an application. When the mouse pointer hovers over the tray icon, the tooltip is displayed. The icon image is automatically resized to fit the space allocated for the image on the tray.

I developed a small Java application for a client a few months back that uses the TrayIcon class called Antons Property Notifier, a desktop alerter for property seekers.

Check it out: www.antons-law.com/properties/antons-property-notifier/ - Available for Download too!

Source Code

  1. import java.awt.AWTException;
  2. import java.awt.Image;
  3. import java.awt.SystemTray;
  4. import java.awt.Toolkit;
  5. import java.awt.TrayIcon;
  6. import java.awt.event.ActionEvent;
  7. import java.awt.event.ActionListener;
  8.  
  9. public class TrayIcon
  10. {
  11. Image image = Toolkit.getDefaultToolkit().getImage("tray.gif");
  12. TrayIcon trayIcon = new TrayIcon(image,"My Tray Icon");
  13.  
  14. public static void main(String[] a) throws Exception
  15. {
  16. if(SystemTray.isSupported())
  17. {
  18. SystemTray tray = SystemTray.getSystemTray();
  19.  
  20. trayIcon.setImageAutoSize(true);
  21. trayIcon.addActionListener(new ActionListener()
  22. {
  23. public void actionPerformed(ActionEvent e)
  24. {
  25. trayIcon.displayMessage("My Tray Icon", "Some Action Performed", TrayIcon.MessageType.INFO);
  26. }
  27. });
  28.  
  29. try
  30. {
  31. tray.add(trayIcon);
  32. }
  33. catch(AWTException e)
  34. {
  35. System.err.println("Tray Icon could not be added.");
  36. }
  37. }
  38. }
  39. }

Share These Free Scripts

My Fancy Artistic Separator

Categories