sap*_*Pro 14 java swing trayicon system-tray jpopupmenu
我想添加JPopupMenu
到任务栏作为TrayIcon
(即 systemTray.add(trayIcon)
),但我还没有找到办法这样做.从文档中,TrayIcon的构造函数如下所示:
public TrayIcon(Image image,
String tooltip,
PopupMenu popup)
Run Code Online (Sandbox Code Playgroud)
有什么方法可以做到这一点吗?
这是一个已知问题.有一个错误报告,其中包含一个变通方法的大纲.我在下面改编了:
// Build your popup menu
final JPopupMenu trayPopup = new JPopupMenu();
// I'm using actions, there are other ways of doing this.
trayPopup.add(someFantaticAction);
// Get your tray icon
trayIcon = new TrayIcon(icon, "My awesome application");
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
@Override
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
trayPopup.setLocation(e.getX(), e.getY());
trayPopup.setInvoker(trayPopup);
trayPopup.setVisible(true);
}
}
});
Run Code Online (Sandbox Code Playgroud)