Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

show and hide a JPopupMenu  RSS feed

 
Harold Lime
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This seems like it should be really simple but I just can't get it to work.

I want a JPopupMenu to appear when the user clicks on a button.

I then when the menu to disappear when the user clicks anywhere other than on the menu.

The only problem I've got is that I'd like the same to happen when the button is clicked a second time.

Logically, to me at least, the following should work:



However, even though I can see the menu, the code always indicates it is not showing and not visible - so the menu never hides again by clicking the button.

Am I missing something?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you trying to reinvent the wheel?
Check out the API docs for JComponent#setComponentPopupMenu and what it does.
 
Harold Lime
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm definitely missing something...

I've look into that, and run this code:
http://www.java2s.com/Code/JavaAPI/javax.swing/JComponentsetComponentPopupMenuJPopupMenupopup.htm

But I still can't figure out how to make it do what I want.

Maybe I'm using a JPopupMenu for something it isn't suitable for?

Basically I want a JButton that works in the same way a JMenuBar. 1 ckick shows the menu, 2nd click hides it again. Clicking anywhere other than the menu should hide the menu also.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've checked your code, and the problem is that the mouse press on the JButton hides the JPopupMenu, leading it to be shown again when the mouse is released.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What Rob said. There were some concurrency issues to sort out, and there may be a better way to do this (I certainly hope so!) but this fulfils the requirements.
 
Harold Lime
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brilliant.

Thanks for the help guys.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!