Java – SystemTray example

This is small example that explain use of SystemTray in java.

What is System Tray : It is an area where small icon of running application will display and show popup messages.

Where is it in windows ?

Below is a image of SystemTray in windows.

Windows System Tray

Here is a example of how to implement SystemTray in your JAVA application.

you can get java.awt.SystemTray object by using static method SystemTray.getSystemTray();

java.awt.SystemTray class contains isSupported() static method. It is use to check whether or not your OS support SystemTray.
TrayIcon this class contains Image that will display in SystemTray.
You can add more then one icons(TrayIcon) in SystemTray using systemTray.add(trayIcon);
To remove icons from SystemTray use systemTray.remove(trayIcon);

In this example I am using omt.gif. It’s size is 35 X 35. You can download from below.

package com.omt.systemtray.main;

import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;

public class Main {

	public static void main(String[] args) {

		if (SystemTray.isSupported()) {
			// Yes My System Support System Tray
			System.out.println("System Try Supported");

			// Create SystemTray and TrayIcon (TrayIcon : It is icon that
			// display in SystemTray)
			final SystemTray systemTray = SystemTray.getSystemTray();
			final TrayIcon trayIcon = new TrayIcon(getImage("omt.gif"),
					"omt is running");
			trayIcon.setImageAutoSize(true);// Autosize icon base on space
											// available on
											// tray

			MouseAdapter mouseAdapter = new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					System.out.println("omt click");
					// This will display small popup message from System Tray
					trayIcon.displayMessage("Omt TrayIcon Demo",
							"This is an info message from TrayIcon omt demo",
							TrayIcon.MessageType.INFO);
				}
			};

			trayIcon.addMouseListener(mouseAdapter);

			try {
				systemTray.add(trayIcon);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	public static Image getImage(String path) {
		ImageIcon icon = new ImageIcon(path, "omt");
		return icon.getImage();
	}

}

Output :
Out Put of SystemTray

After Click on Icon

Share