I’m currently creating a right-click context menu by instantiating a new JMenu on right click and setting its location to that of the mouse’s position… Is there a better way?
I’m currently creating a right-click context menu by instantiating a new JMenu on right
Share
You are probably manually calling
setVisible(true)on the menu. That can cause some nasty buggy behavior in the menu.The
show(Component, int x, int x)method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where usingsetVisible(true)just shows the menu without adding any additional behavior.To make a right click popup menu simply create a
JPopupMenu.Then, all you need to do is add a custom
MouseListenerto the components you would like the menu to popup for.Of course, the tutorials have a slightly more in-depth explanation.
Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the
e.getXOnScreen()ande.getYOnScreen()methods for the x and y coordinates.