在点击java.awt.MenuItem

时间:2018-12-07 10:49:17

标签: java awt mouseevent

我想区分java.awt.MenuItem上的鼠标左键和鼠标右键。当前,两个事件都触发相同的ActionListener,但我无法找出已按下哪个鼠标按钮。

选择KeyEvents(鼠标悬停,未单击);-)的任何解决方案的奖励积分,也可以识别MenuItem;-p

背景

我已经创建了TrayIcon,并添加了PopupMenu。我不使用Swing UI元素,因为在菜单外部(例如在桌面上)单击时,我还没有找到隐藏弹出菜单的方法。这就是为什么我坚持使用AWT组件。

示例代码

public void createSystemTrayMenu() {
    // Create System Tray Icon
    SystemTray systemTray = SystemTray.getSystemTray();
    TrayIcon trayIcon = new TrayIcon(
            Toolkit.getDefaultToolkit().getImage(Constants.TRAY_ICON_FILENAME),
            Constants.TRAY_ICON_TEXT);
    PopupMenu testMenu = new PopupMenu();

    MenuItem testItem = new MenuItem("Test", new MenuShortcut(KeyEvent.VK_SPACE));
    testItem.addActionListener(new ActionListener() {@Override
        public void actionPerformed(ActionEvent e) {
            // Here I want to know which mouse button has been pressed to get here
            doSomething();
        }
    });

    testMenu.add(testItem);
    trayIcon.setPopupMenu(testMenu);

    try {
        systemTray.add(trayIcon);
    } catch (AWTException e) {
        e.printStackTrace();
    }
}

0 个答案:

没有答案