how-to

Others

How to add icon with popup menu to system tray

For this example you need:

import java.awt.*;

When you need to add popup menu into system icon tray, add this menu in icon tray constructor as parameter - or set it after icon tray creation. That popup menu is displayed after right mouse button click on icon tray.

/* -- is supported by System ? */
if ( ! SystemTray.isSupported() ) return;

/* -- get system tray */

final SystemTray tray = SystemTray.getSystemTray();
System.out.println( tray.getTrayIconSize().toString() );

/* -- load image */

Image image = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource( "/resource/pict2.png" ) );

/* -- create tray icon */

TrayIcon trayicon = new TrayIcon( image, "This is tray icon.." );
trayicon.setImageAutoSize( true );

/* -- create popup menu */

PopupMenu popup = new PopupMenu();

/* - first menu option */
MenuItem item1 = new MenuItem( "Exit" );
item1.addActionListener( new ActionListener() {

  @Override
  public void actionPerformed(ActionEvent e) {
    /* remove tray icon */
    tray.remove( trayicon );
  }

});
popup.add( item1 );

popup.addSeparator();

/* - second menu option */
MenuItem item2 = new MenuItem( "Item2" );
popup.add( item2 );

/* set popup menu */
trayicon.setPopupMenu( popup );

/* -- add tray icon to system tray */

try {
  tray.add( trayicon );
} catch (AWTException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

After right mouse button click on the icon is displayed this popup menu: