概要

JDK 6で追加された機能を使って、SystemTrayにアイコンを表示します。

サンプルコード

public MainPanel(final JFrame frame) {
  super();
  if (!SystemTray.isSupported()) {
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    return;
  }
  SystemTray tray = SystemTray.getSystemTray();
  Image image = new ImageIcon(getClass().getResource("16x16.png")).getImage();
  PopupMenu popup = new PopupMenu();
  TrayIcon icon   = new TrayIcon(image, "TRAY", popup);

  MenuItem item1 = new MenuItem("OPEN");
  item1.addActionListener(new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
      frame.setVisible(true);
    }
  });
  MenuItem item2 = new MenuItem("EXIT");
  item2.addActionListener(new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
      tray.remove(icon);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.dispose();
      // System.exit(0);
    }
  });
  popup.add(item1);
  popup.add(item2);

  try {
    tray.add(icon);
  } catch (AWTException e) {
    e.printStackTrace();
  }
}
View in GitHub: Java, Kotlin

解説

  • デフォルトのTrayIconでは、JPopupMenuではなくPopupMenuMenuItemが使用される
  • 上記のサンプルでは、フレームがアイコン化(最小化)されたときにタスクバーの表示を消して、システムトレイにアイコンだけ表示したいので、初期状態をframe.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);にし、アイコン化された場合でもframe.dispose();するように設定
    • 実際にVMを終了する場合は、表示可能なウィンドウをすべて破棄してからtray.remove(icon);を実行してシステムトレイのアイコンを取り除く必要がある

参考リンク

コメント