• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:SystemTrayにアイコンを表示
#navi(../)
*SystemTrayにアイコンを表示 [#n4a8cf0f]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-03-05~
更新日:&lastmod;

#contents

**概要 [#n5dc9de9]
JDK 6 で追加された機能を使って、SystemTrayにアイコンを表示します。

#screenshot

**サンプルコード [#ie1fffe5]
#code{{
 public MainPanel(final JFrame frame) {
   super();
   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);
 
   MenuItem item1 = new MenuItem("OPEN");
   item1.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       frame.setVisible(true);
     }
   });
   MenuItem item2 = new MenuItem("EXIT");
   item2.addActionListener(new ActionListener() {
     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();
   }
 }
}}
//-&jnlp;
-&jar;
-&zip;

**解説 [#g1110d96]
トレイアイコンでは、JPopupMenuではなく、PopupMenuやMenuItemを使用します。

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

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

//**参考リンク
**コメント [#na7a06ee]
- Ubuntu だと通知スペースに表示されるのですが、背景色や位置がどうもうまくいっていないようです。 -- [[terai]] &new{2007-05-08 (火) 20:23:38};
-- 位置は以下みたいにすれば適当に補正できそうですが、背景色はどうしたらいいんだろう? g.setColor(UIManager.getColor("Panel.background"));g.fillRect(0,0,d.width,d.height);とかするのは酷いか…。 -- [[terai]] &new{2007-05-08 (火) 21:11:09};
#code{{
SystemTray tray = SystemTray.getSystemTray();
Dimension d = tray.getTrayIconSize();
//Image image = new ImageIcon(getClass().getResource("16x16.png")).getImage();
BufferedImage image = new BufferedImage(d.width,d.height,BufferedImage.TYPE_INT_ARGB);
ImageIcon i = new ImageIcon(getClass().getResource("16x16.png"));
Graphics g = image.createGraphics();
i.paintIcon(null,g,(d.width-i.getIconWidth())/2,(d.height-i.getIconWidth())/2);
g.dispose();
PopupMenu popup = new PopupMenu();
TrayIcon icon   = new TrayIcon(image, "TRAY", popup);
}}
-- g.setBackground(new Color(0,0,0,0));g.clearRect(0,0,d.width,d.height);とかしても変化無し。 -- [[terai]] &new{2007-05-09 (水) 13:54:25};

#comment