Java弹出菜单监听项目点击



我用以下代码创建了一个非常简单的托盘菜单:

        final Frame frame = new Frame("");
            frame.setUndecorated(true);
            // Check the SystemTray is supported
            if (!SystemTray.isSupported()) {
                System.out.println("SystemTray is not supported");
                return;
            }
            final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
                    new URL("http://url.com/trayIcon.png")), "Library Drop");
            final SystemTray tray = SystemTray.getSystemTray();
            // Create a pop-up menu components
            final PopupMenu popup = createPopupMenu();
            trayIcon.setPopupMenu(popup);
            trayIcon.addMouseListener(new MouseAdapter() {
                //@Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        frame.add(popup);
                        popup.show(frame, e.getXOnScreen(), e.getYOnScreen());
                    }
                }
            });
            try {
                frame.setResizable(false);
                frame.setVisible(true);
                tray.add(trayIcon);
            } catch (AWTException e) {
                System.out.println("TrayIcon could not be added.");
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }

    protected static PopupMenu createPopupMenu() {
        final PopupMenu popup = new PopupMenu();
        MenuItem aboutItem = new MenuItem("Accept");
        MenuItem aboutItem1 = new MenuItem("Dont accept");
        MenuItem aboutItem2 = new MenuItem("Quit");            

        // Add components to pop-up menu
        popup.add(aboutItem);
        popup.add(aboutItem1);            
        popup.addSeparator();
        popup.add(aboutItem2);            

        return popup;
    }

当用户选择"接受"、"不接受"等时,我如何倾听和检查?

同样由于某种原因,托盘图标的高度是最大的,我如何才能告诉托盘图标是X乘Y像素?

编辑:高度/宽度问题仅适用于Mac,在Windows 上运行良好

只需在MenuItem s上使用addActionListener

MenuItem aboutItem = new MenuItem("Accept");
aboutItem.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Accept clicked!");
    }
});

此外,如果您碰巧使用Java 8或更高版本,它会变得更简单:

MenuItem aboutItem = new MenuItem("Accept");
aboutItem.addActionListener(evt -> System.out.println("Accept clicked!"));

相关内容

  • 没有找到相关文章

最新更新