How do I get a PopupMenu to show up when I left-click on a TrayIcon in Java?

前端 未结 2 1845
臣服心动
臣服心动 2020-12-10 23:39

Currently, the PopupMenu will show up when I right-click on the TrayIcon in the SystemTray. However, I want it to do the same when I left-click on the TrayIcon.

I th

2条回答
  •  不知归路
    2020-12-11 00:10

    What you're trying to do is apparently not possible:

    You cannot show the PopupMenu with its show method since you need to specify a JComponent but your TrayIcon isn't one (weird enough though that TrayIcon still manages to do it, so apparently there is a way, don't ask me though..). So, as MadProgrammer suggested, you should try using JPopupMenu instead. Don't add it to your TrayIcon for that won't be possible, but display your JPopupMenu by adding a MouseListener to your TrayIcon. That should do the trick:

    final TrayIcon tray = new TrayIcon( img, tooltip, null);
    final JPopupMenu menu = new JPopupMenu();
    ... // your menu initialization.
    tray.addMouseListener( new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent evt) {
            menu.setLocation( evt.getPoint() );
            menu.setVisible( true );
        }
    }
    

提交回复
热议问题