SystemTray Icon for Java Swing Application
Sometimes we need our application to be launched hidden in background. Applications like Skype or ICQ are running in background and waiting for incoming messages. These applications both having their icon in the System Tray and you can easily activate them by double-clicking on their system tray icon. This tutorial shows how to create the System Tray Icon for your Java Swing Application.
One problem, however, is that you need to have JRE 6 installed. Previous versions of Java VM do not support System Tray.
Creating SystemTray Icon
Firstly, we need to have the following packages imported:
import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.TrayIcon.MessageType;
Let's declare a SystemTray variable
TrayIcon trayIcon = null;
Then we need to check if the SystemTray is supported.
if (SystemTray.isSupported()) ...
If it is, then we will create a new TrayIcon. To create the TrayIcon we need to specify the Icon (or you can use the standard Java Icon), application name and a PopupMenu to be shown on right click.
// getting image to be used as icon for our TrayIcon
URL iconURL = getClass().getResource("/graphics/rss.png");
ImageIcon icon = new ImageIcon(iconURL);
// Creating popup menu to be shown on right click trayMenu = new PopupMenu(); // Shows or hides main frame popupShowHide = new MenuItem("Show/Hide"); popupShowHide.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { frame.setVisible(!frame.isVisible()); } }); trayMenu.add(popupShowHide); // close application MenuItem popupExit = new MenuItem("Exit"); popupExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { closeApplication(); } }); trayMenu.add(popupExit);
// Create TrayIcon trayIcon = new TrayIcon(icon.getImage(), // Image "My Application", // Caption Text trayMenu // Popup Menu ); // shrink image to the size of the tray icon trayIcon.setImageAutoSize(true); // instance of SystemTray SystemTray systemTray = SystemTray.getSystemTray(); // trying to add the TrayIcon try { systemTray.add(trayIcon); } catch (AWTException ignore) { // ignore }
Also, you can catch the left double click on the TrayIcon. Say, for example you want to activate your application on left double click. Just add and ActionListener like this.
trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.setVisible(!frame.isVisible());
}
});
SystemTray notifications
SystemTray allows you to show notifications about some events that has occured.
public void showInformation(String message) {
trayIcon.displayMessage("My Application", // Application Title
message, // Message to be shown
MessageType.INFO // Type of the message - INFO
);
}
For more information visit java.sun.com website.