TITLE:SystemTrayにアイコンを表示
Posted by terai at 2007-03-05

SystemTrayにアイコンを表示

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

概要

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

#screenshot

サンプルコード

#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
public MainPanel(final JFrame frame) {
  super();
  if(!SystemTray.isSupported()) {
  if (!SystemTray.isSupported()) {
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    return;
  }
  frame.addWindowStateListener(new WindowAdapter() {
    public void windowIconified(WindowEvent e) {
      frame.dispose();
    }
  });
  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);
  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() {
    public void actionPerformed(ActionEvent e) {
    @Override public void actionPerformed(ActionEvent e) {
      frame.setVisible(true);
    }
  });
  MenuItem item2 = new MenuItem("EXIT");
  item2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    @Override public void actionPerformed(ActionEvent e) {
      tray.remove(icon);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.dispose();
      //System.exit(0);
      // System.exit(0);
    }
  });
  popup.add(item1);
  popup.add(item2);

  try{
  try {
    tray.add(icon);
  }catch(AWTException e) {
  } catch (AWTException e) {
    e.printStackTrace();
  }
}

解説

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

解説

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

参考リンク

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

コメント