At some point every Java developer who creates GUIs (Graphical User Interfaces) will want to be able to load their application into the system tray (the notification area at the bottom right of a Windows desktop).
Anyone new to Java programming may expect this to be difficult, but any seasoned Java programmers will realize immediately that it's just a matter of including the right packages and classes. The trick is to know which ones to load.
Java System Tray Packages
Java is an object oriented language and so all of its functionality is contained in classes, and classes are stored in packages. In order to use the system tray it is just a matter of the programmer loading the correct packages. Fortunately these are the same ones that are required for any standard GUI application:
Once the packages have been loaded the programmer can turn their attention to the new class that will use the system tray.
Access the System Tray with Java
The new class extends the Swing JFrame class and then uses the SystemTray.getSystemTray method to access the system tray itself.
When the application accesses the system tray it will do to things:
- display an icon in the system tray
- display a popup menu when the icon is clicked
Both of these actions are, of course, quite easy to implement.
Loading an Icon Image
The image is loaded by making use of the Awt toolkit:
The original image should be 16 pixels by 16 pixels in order for it to be displayed correctly in the system tray.
Creating a Popup Menu
The creation of a popup menu is a very simple process:
- create a PopupMenu object
- create one or more MenuItem objects
- define an action for the menu item
- add the MenuItem object to the PopupMenu object
In this example a single item is added to the popup menu and that is used to close the application:
The application is now ready to be added to the system tray.
Creating a Tray Icon
As always with Java any hard work is done be adding another class - in this case it's the TrayIcon class:
And then everything is run in the Main method:
If this is saved (as trayDemo.java), compile and run then a neat little icon will appear in the system tray.
Summary
A Java programmer can easily add an application to the system tray by:
- including the Swing and Awt packages
- creating a system tray object
- creating an image object
- creating a popup menu
- using the image an the popup menu to create a system tray icon
- adding the system tray icon to the system tray
And at the end of the process the programmer will have a Java application that can be added to the system tray.