Swing/SystemTray のバックアップの現在との差分(No.19)
- category: swing folder: SystemTray title: SystemTrayにアイコンを表示 tags: [SystemTray, Icon] author: aterai pubdate: 2007-03-05 pubdate: 2007-03-05T02:26:31+09:00 description: JDK 6で追加された機能を使って、SystemTrayにアイコンを表示します。 image:
概要
JDK 6
で追加された機能を使って、SystemTray
にアイコンを表示します。
Screenshot
Advertisement
サンプルコード
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);
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);
// System.exit(0);
}
});
popup.add(item1);
popup.add(item2);
try {
tray.add(icon);
} catch (AWTException e) {
e.printStackTrace();
}
}
View in GitHub: Java, Kotlin解説
トレイアイコンでは、JPopupMenu
ではなく、PopupMenu
やMenuItem
を使用します。
- デフォルトの
TrayIcon
では、JPopupMenu
ではなくPopupMenu
やMenuItem
が使用される - 上記のサンプルでは、フレームがアイコン化(最小化)されたときにタスクバーの表示を消して、システムトレイにアイコンだけ表示したいので、初期状態を
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);
してアイコンを取り除けばいいようです。