(Java) JPopupMenu does not close if I click on it

I created a Java Swing application that does not have a visible main window, but which is controlled through the tray icon by right-clicking.

I use JPopupMenu for this, but when I go beyond the popup menu (for example, in another application window or on the desktop), JPopupMenu does not disappear, which is not the expected behavior.

I initially used popupMenu, which worked as expected, but that did not allow me to have icons on the menu.

How can I close it when I'm clicking elsewhere, as expected?

Thanks!

+6
java
source share
3 answers

In the end, I “solved” this by cracking the problem. As Camicre points out, JPopupMenu is pretty buggy. However, this is the only implementation of the Swing popup menu that allows you to have an icon next to each menu item.

My solution was to implement a jpopupmenu listener which, if the user placed the mouse on the menu, after 3 seconds would be set to .isVisible (false) if the user did not put the mouse back on the menu during this time.

To achieve this, I had to use a separate thread that constantly checked if popupmenu was active. If so, check if the mouse was above it using the event listener and set the visibility to false if the user does not enter it again within 3 seconds.

This is not an ideal solution, as the user still needs to wait 3 seconds for the menu to disappear (it should be instantaneous if he / she clicks) and it will disappear even if it is in focus (he should not the user presses the button ) However, he felt "good enough" to accept.

Hope this helps.

+2
source share
//_Popup is your JPopupMenu, call this method before setting your popup to visible public void armPopup() { if(_Popup != null) { Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { @Override public void eventDispatched(AWTEvent event) { if(event instanceof MouseEvent) { MouseEvent m = (MouseEvent)event; if(m.getID() == MouseEvent.MOUSE_CLICKED) { _Popup.setVisible(false); Toolkit.getDefaultToolkit().removeAWTEventListener(this); } } if(event instanceof WindowEvent) { WindowEvent we = (WindowEvent)event; if(we.getID() == WindowEvent.WINDOW_DEACTIVATED || we.getID() == WindowEvent.WINDOW_STATE_CHANGED) { _Popup.setVisible(false); Toolkit.getDefaultToolkit().removeAWTEventListener(this); } } } }, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK); } } 
+6
source share

Errors are known when using JPopupMen: JTrayIcon: Swing support for JPopupMenus for tray icons . Towards the end - this is a link to a possible solution. I have not tried, so I do not know if this will fix your problem or not.

+2
source share

All Articles