File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes JMenu ActionPerformed Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JMenu ActionPerformed Question" Watch "JMenu ActionPerformed Question" New topic
Author

JMenu ActionPerformed Question

Dennis Putnam
Ranch Hand

Joined: Feb 03, 2012
Posts: 217
I am implementing menus using JMenu. I have recently encountered a problem that I don't know how to resolve. I have 2 menus that happen to have the same named JMenuItem. In order to resolve this I need to determine which JMenu the JMenuItem came from. However, I don't see how to determine that from what is available in the ActionEvent object. What am I missing? TIA.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
ActionEvent.getSource()?
Dennis Putnam
Ranch Hand

Joined: Feb 03, 2012
Posts: 217
Nope. That tells me the JMenuItem not the JMenu.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
SwingUtilities.getAncestorOfClass(..) might suit

[edit]

actually, you still might be able to use getSource()

each component has a 'name' property.
use this to ID the JMenu.
Dennis Putnam
Ranch Hand

Joined: Feb 03, 2012
Posts: 217
Thanks but neither of those worked for me. Both returned null.

null pointer exception

printed null
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
Looks like non‑object‑oriented programming to me. Give each menu item its own action listener. Then that problem will not occur.
Dennis Putnam
Ranch Hand

Joined: Feb 03, 2012
Posts: 217
That was what I was thinking. Each JMenu has to have its own ActionPerformed method. Its probably easier for me to just avoid duplicating JMenuItems buy altering the names slightly. Thanks.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19783
    
  20

FYI, JMenu using=(JMenu) SwingUtilities.getAncestorOfClass(getClass(), source); will try to find an ancestor component of this class. If you want a JMenu, replace getClass() with JMenu.class (the Class object for JMenu).

But I agree that a separate ActionListener (or even better - Action) is a much cleaner solution.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JMenu ActionPerformed Question