System tray icon : TrayIcon « JDK 6 « Java






System tray icon

   

import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.plaf.metal.MetalIconFactory;

public class SysTray {
  public static void main(String[] args) throws Exception {
    new SysTray().installSystemTray();
  }

  public void installSystemTray() throws Exception {
    PopupMenu menu = new PopupMenu();
    MenuItem exit = new MenuItem("Exit");
    exit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.exit(0);
      }
    });
    menu.add(exit);
    
    TrayIcon icon = new TrayIcon(getImage(), "Java application as a tray icon", menu);
    icon.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "Hi!");
      }
    });
    SystemTray.getSystemTray().add(icon);
    Thread.sleep(3000);
    icon.displayMessage("Attention", "Please click here", TrayIcon.MessageType.WARNING);
  }

  private Image getImage() throws HeadlessException {
    Icon defaultIcon = MetalIconFactory.getTreeHardDriveIcon();
    Image img = new BufferedImage(defaultIcon.getIconWidth(), defaultIcon.getIconHeight(),
        BufferedImage.TYPE_4BYTE_ABGR);
    defaultIcon.paintIcon(new Panel(), img.getGraphics(), 0, 0);
    return img;
  }

}

   
    
    
  








Related examples in the same category

1.Create Tray Icon
2.Remove Icon from TrayIcon
3.Add mouse listener to TrayIcon
4.Add Mouse motion listener to TrayIcon
5.Using system tray
6.Demonstrating a System Tray That Responds to Selection
7.Add PropertyChangeListener to TrayIcon
8.Have a systray icon (Windows)
9.This program demonstrates the system tray API.