Question

I'm working on a simple Java swing app, which adds an icon to the system tray when created. What I'm trying to do is to detect when this icon is single clicked by the user (whether through left click or right click), There's no popup menu, I just want the app to be restored when the icon is clicked.

This is the code I'm using:

    SystemTray tray = SystemTray.getSystemTray(); 
    Image icon = toolkit.getImage("icon.png");

    ActionListener listener = new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("click detected");
        }
    };

    TrayIcon trayIcon = new TrayIcon(icon, "Test Program", null);
    trayIcon.addActionListener(listener);
    tray.add(trayIcon);

What happens when I run this program though, is that single clicks (either left or right) have no effect, but when I double click, then it shows the message 'click detected' in the console.

What can I do to have single clicks also be detected? Do I need to use a MouseListener for this? ( I've heard that MouseListeners can cause problems, and ActionListeners are better)

Était-ce utile?

La solution

You could use MouseListener, ie:

trayIcon.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 1) {

        }
    }
}); 

See How to Write a Mouse Listener for more details.

EDIT: ActionListener vs MouseListener

There is a concept of low level and semantic events. Whenever possible, you should listen for semantic events rather than low-level events, such as listening for action events, rather than mouse events. Read for more details in Low-Level Events and Semantic Events.

In this case you just need more details from the event so using MouseListener is required.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top