Search code examples
javaswingclickjpopupmenujmenu

Open popupMenu only on mouse-click Swing


I have a question related with JPopupMenu that maybe someone can help me.

As far as I can see, a JPopupMenu opens when you press a JMenu (is this is in a JMenuBar) or when you hover over a JMenu (if this is in a JPopupMenu).

So, I have a JMenuBar containing a JMenu (let's call it 'File'). When I press 'File', a JPopupMenu open, which contains a JMenuItem and another JMenu (let's call it 'Properties'). Is there any way I can apply the same behaviour to the Properties JMenu as I have in the File JMenu: only opens the JPopup when the user click it and not hover over it?

I know this is trying to avoid the normal behavior for the JMenu, but any of you have an idea if this is possible?


Solution

  • This is something very specific and I dont know if there are many people doing this. :) Anyway, I leave a solution for this in case someone needs it.

    First is important to notice that these changes are done in the UI classes. Both BasicMenuItemUI and BasicMenuUI have a inner class Handler that take care about the mouse events. The inner class Handler in the BasicMenuUI extends the inner class Handler in the BasicMenuItemUI and because they private and anonymous (respectively) is hard to change the code. But, in both cases, there are a protected Handler which points to the Handlers I talked in the previous paragraph.

    So, as a solution I extended those protected handlers in my own MyOwnBasicMenuUI and MyOwnBasicMenuItemUI implementations and I applied my own behavior. Now I have a JMenu which only opens when the user clicks it, and remains open till the user clicks somewhere else. If someone wants more details, I can provide them.

    Thanks