• category: swing folder: SystemTray title: SystemTrayにアイコンを表示 tags: [SystemTray, Icon] author: aterai pubdate: 2007-03-05 description: JDK 6で追加された機能を使って、SystemTrayにアイコンを表示します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTUJeisovI/AAAAAAAAAlk/zvAoP96Ntcs/s800/SystemTray.png

概要

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

サンプルコード

public MainPanel(final JFrame frame) {
  super();
  if (!SystemTray.isSupported()) {
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    return;
  }
  final SystemTray tray = SystemTray.getSystemTray();
  final Image image     = new ImageIcon(
    getClass().getResource("16x16.png")).getImage();
  final PopupMenu popup = new PopupMenu();
  final 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

解説

トレイアイコンでは、JPopupMenuではなく、PopupMenuMenuItemを使用します。

上記のサンプルでは、フレームがアイコン化(最小化)されたときにタスクバーの表示を消して、システムトレイにアイコンだけ表示したいので、初期状態をframe.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);にしておき、アイコン化された場合でも、frame.dispose();するようにしています。

実際にVMを終了する場合は、表示可能なウィンドウをすべて破棄して(frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);)、システムトレイからもtray.remove(icon);してアイコンを取り除けばいいようです。

参考リンク

コメント