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?
//_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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With