Why does Java's AWT's tray icon swallow events when displaying a message?

若如初见. 提交于 2020-01-06 07:28:07

问题


Using Java 8 and AWT I'm displaying a tray icon on Windows 10. I also use the tray icon to display notifications. While displaying this notification, the mouse listener in the icon won't issue the first pressed and clicked event.

Here's the minimum example:

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class TrayIconDemo {
    public static void main(String[] args) {
        createTrayIcon();
    }

    private static void createTrayIcon() {
        Image image = Toolkit.getDefaultToolkit().getImage(TrayIconDemo.class.getResource("/foo.png"));
        final TrayIcon trayIcon = new TrayIcon(image);

        trayIcon.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                System.out.println("Mouse Clicked");
            }

            public void mousePressed(MouseEvent e) {
                System.out.println("Mouse Pressed");
            }

            public void mouseReleased(MouseEvent e) {
                System.out.println("Mouse Released");
            }
        });

        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }

//        trayIcon.displayMessage("title", "message", TrayIcon.MessageType.NONE);
    }
}

If you run the example as is and click the icon twice, you get the expected six events (three for each click):

Mouse Pressed
Mouse Released
Mouse Clicked
Mouse Pressed
Mouse Released
Mouse Clicked

Now, if you uncomment the last line, the one that calls displayMessage, then you get the little message:

but if you click the icon twice, instead you get:

Mouse Released
Mouse Pressed
Mouse Released
Mouse Clicked

The initial pressed and clicked events are swallowed somewhere. Why is that?

When you click the tray icon, the message doesn't go away. If you dismiss the message, then the tray icon works as expected with all 6 events.

Here's a video showing the issue:

https://www.youtube.com/watch?v=eV2Lwim2EcY

来源:https://stackoverflow.com/questions/50278371/why-does-javas-awts-tray-icon-swallow-events-when-displaying-a-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!