Java弹出菜单监听项目点击?

时间:2013-09-01 19:50:10

标签: java swing awt system-tray jpopup

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

        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上正常工作

1 个答案:

答案 0 :(得分:4)

只需在MenuItem上使用addActionListener

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