Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPopupMenu won't close if I click outside of it

Tags:

java

swing

I have created a Java Swing app that has no visible main window but which is controlled through its tray icon by right-clicking.

I am using a JPopupMenu for this, but when I click outside of the popup menu (e.g. on another application's window or the desktop) the JPopupMenu does not disappear which is not the expected behaviour.

Originally I was using a popup menu which did work as expected but this did not allow me to have icons in the menu.

How can I get it to close when I click elsewhere, as expected?

like image 232
Danny King Avatar asked Apr 18 '10 12:04

Danny King


1 Answers

//_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);

    }
}
like image 168
Kezine Avatar answered Sep 20 '22 07:09

Kezine