This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JMenu keep open with right click Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JMenu keep open with right click" Watch "JMenu keep open with right click" New topic

JMenu keep open with right click

Raymond du Toit

Joined: Jun 29, 2005
Posts: 6
I need help with a mouse listener on a menu I made.
I added a mouse listener to the each Menu item. If a user left clicks the menu item, it opens the option. But if he right clicks on the menu item, it should keep the menu open and display the right click popup menu. I got the popup menu to display on right click, but the menu closes, so the user cannot see which item he right clicked on.

Is it possible to override the default close operation of Jenu and keep the menu open until I left click on the menu item?

Thank You
Rob Spoor

Joined: Oct 27, 2005
Posts: 19911

I haven't tried it, but if you consume your event (e.consume()) it should work. From the InputEvent API (MouseEvent is a subclass):
For example, consuming mousePressed events on a Button component will prevent the Button from being activated.

How To Ask Questions How To Answer Questions
Raymond du Toit

Joined: Jun 29, 2005
Posts: 6
e.consume() does not seem to work on JMenuItems.
It only seems to work on buttons. If I put an operation and e.consume() in one of the MouseListener methods, it seems to ignore e.consume(), executes the operation and closes the menu.

Thanx anyway!
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
wouldn't it be simpler to add the r/click options to the menu
as subitems (or whatever it's called - displays the > arrow)
Raymond du Toit

Joined: Jun 29, 2005
Posts: 6
Sounds like a good idea, thanx. I will try that.
I agree. Here's the link:
subject: JMenu keep open with right click