Reputation: 39204
I'm using a JPopupMenu displayed when I do a right click on certain components in my GUI.
Now I have to destroy the popup menu displayed in this 2 situation:
I solved this problem storing into an ArrayList the current visible popups and I manually set them to be invisible when one of the 2 previous situation occured.
So, i would like to know 2 things:
It is a bit difficult to show my actual code, because it's a bit complex. Anyway it does the following:
public EditorPopupMenu getPopupMenu() {
this.popupMenu = new EditorPopupMenu();
EditorMenuItem copy = GuiConcreteFactory.getInstance().createMenuItem(Gui.getInstance().copyItemAction);
EditorMenuItem cut = GuiConcreteFactory.getInstance().createMenuItem(Gui.getInstance().cutItemAction);
EditorMenuItem paste = GuiConcreteFactory.getInstance().createMenuItem(Gui.getInstance().pasteItemAction);
this.popupMenu.add(copy);
this.popupMenu.add(cut);
this.popupMenu.add(paste);
this.popupMenu.addSeparator();
EditorMenuItem settings = GuiConcreteFactory.getInstance().createMenuItem(
new ApplicationShowDialogAction("settings",null,
new EditorAreaDialog (this)) );
this.popupMenu.add(settings);
return popupMenu;
}
Where EditorPopupMenu extends JPopupMenu. Previous code is called by a MouseListener when a click happend on a particular object and the specified object constructs its popup menu and returns it.
From inside the MouseListener:
if (me.getModifiers() == InputEvent.BUTTON3_MASK){
// //System.out.println("ResizableMouseAdapter: BUTTON_3_MASK");
EditorPopupMenu popupMenu = sourceComp.getType().getPopupMenu();
if ( popupMenu!= null){
//System.out.println("COMPONENT HAS A POPUP MENU");
popupMenu.setLocation( sourceComp.getLocationOnScreen().x + me.getX(),
sourceComp.getLocationOnScreen().y + me.getY());
popupMenu.setVisible(true);
Gui.getInstance().addActivePopup(popupMenu);
}
}
This is all. With this code my JPopupMenu doesn't dissapear properly.
Upvotes: 1
Views: 3903
Reputation: 324207
This is the default behaviour.
Read the section from the Swing tutorial on Bringing Up a Popup Menu for an explanation and working example.
Upvotes: 1