Question

Im creating a very simple tray menu with the following code:

        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;
    }

How can i listen and check when a user selects "Accept", "Dont accept", etc?

Also for some reason the height is maximum on the trayIcon, how can i tell the tray icon to be exactly X by Y pixles?

Edit: height/width issue is only in Mac, works fine on Windows

Était-ce utile?

La solution

Simply use addActionListener on your MenuItems.

MenuItem aboutItem = new MenuItem("Accept");
aboutItem.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Accept clicked!");
    }
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top