Forums Register Login

JMenu ActionPerformed Question

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
ActionEvent.getSource()?
+Pie Number of slices to send: Send
Nope. That tells me the JMenuItem not the JMenu.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Thanks but neither of those worked for me. Both returned null.

null pointer exception

printed null
+Pie Number of slices to send: Send
Looks like non‑object‑oriented programming to me. Give each menu item its own action listener. Then that problem will not occur.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
It sure was nice of your sister to lend us her car. Let's show our appreciation by sharing this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1362 times.
Similar Threads
coding a texteditor: want to open a separate option window
Adding JMenus to EditPanes
Separating the Fraim from Menu
How to add JMenuItem to my JMenu??
Things arn't showing up...
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 04:30:07.