Start my Windows application in System Tray

10

I have no idea how I make my application start with Windows 7 already in System Tray mode. That is, start with Windows and get the program icon next to the Windows 7 clock.

    
asked by anonymous 12.05.2014 / 16:09

1 answer

9

Basically what you should do is take the instance of SystemTray from your operating system and add a new object of type TrayIcon custom to it.

TrayIcon is the object you are going to work on. Once created, add an image to it, usually a menu is also added for a user interface.

To create this menu you should create a PopupMenu and add a MenuItem to it with the options you want.

Example:

import java.awt.*;
public class MeuTray {
  public static void main(String args[]) {
    Runnable runner = new Runnable() {
      public void run() {
        if (SystemTray.isSupported()) {
          SystemTray tray = SystemTray.getSystemTray();
          Image image = Toolkit.getDefaultToolkit().getImage("imagem.gif");
          PopupMenu popup = new PopupMenu();
          MenuItem item = new MenuItem("Um MenuItem");
          popup.add(item);
          TrayIcon trayIcon = new TrayIcon(image, "Texto de dica", popup);
          trayIcon.setImageAutoSize(true); 
          try {
            tray.add(trayIcon);
          } catch (AWTException e) {
            System.err.println("Não pode adicionar a tray");
          }
        } else {
          System.err.println("Tray indisponível");
        }
      }
    };
    EventQueue.invokeLater(runner);
  }
}

Result:

Using the following image as an icon:

Hoveringovertheicon:

Right-clicking the icon:

AddmoreoptionsinyourMenuItemandtreateventswhentheuserselectstheMenuItemitem.

Sources:
Java Tutorials - How to Use the System Tray < Oracle Tech Tips - Getting to Know Tray System

Oracle Tech Tips - Getting to Know Tray System

    
12.05.2014 / 17:07