aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Sharing JMenuItems Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Sharing JMenuItems" Watch "Sharing JMenuItems" New topic
Author

Sharing JMenuItems

Jess Ryan
Greenhorn

Joined: Feb 16, 2008
Posts: 21
Ok, I'm stumped. I've searched the 'net but found nothing... probably because no one else in the world has ever encountered this issue.

The situation is that I've got a few menu items that I want to share between an edit menu (in a jmenubar) and a popup menu. I build the popup menu first, then add the menu bar. Here's the 'issue' part: when I add the shared menu items to the edit menu, they are removed from the popup menu.. AND, only one is added to the edit menu (where, for example, there are 4 menu items that I'm adding). What in the world is happening? Below is a runnable example that just prints out the number of items in the menus to show my point.

Any insight will be hugely appreciated!

Philippe Nizer
Greenhorn

Joined: Nov 12, 2008
Posts: 3
Hi Jess,

I think it is a normal behavior of swing. JMenuItems can belong to only one JMenu. I resolved my problem creating a method that always returns a new JMenuItem.

Regards,
Philippe.
Jess Ryan
Greenhorn

Joined: Feb 16, 2008
Posts: 21
Ah. Alrighty, I'll do the same. Thanks!!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39818
    
  28
"Philippe" please read the important administrative private message I just sent you.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39818
    
  28
Philippe is correct; you cannot have the same JComponent in two different places.
What you actually need is to add the same ActionListener object to both JMenuItems.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

You can use Action objects (hint: extend AbstractAction) to do all the hard work. These Action objects can be shared among multiple user interface components; buttons, menu items, basically anything that can accept an Action.

If you then disable this single shared Action object, all components that are created with it will also get disabled.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jess Ryan
Greenhorn

Joined: Feb 16, 2008
Posts: 21
Thanks everyone!

Actions sound like a good solution. I just may do that when it's refactor time.

Thanks again!
 
Don't get me started about those stupid light bulbs.
 
subject: Sharing JMenuItems