我创建了一个
Java Swing应用程序,该应用程序没有可见的主窗口,但通过右键单击可通过其托盘图标进行控制.
我正在使用JPopupMenu,但是当我点击弹出菜单之外(例如在另一个应用程序的窗口或桌面上)时,JPopupMenu不会消失,这不是预期的行为.
最初我使用的是popupMenu,它按预期工作,但这不允许我在菜单中有图标.
如我所说,当我点击其他地方时,如何让它关闭?
谢谢!
//_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);
}
}