Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JMenu ActionPerformed Question

 
Dennis Putnam
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ActionEvent.getSource()?
 
Dennis Putnam
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope. That tells me the JMenuItem not the JMenu.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks but neither of those worked for me. Both returned null.

null pointer exception

printed null
 
Campbell Ritchie
Sheriff
Posts: 48642
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20510
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic