0

I have Place a JMenuBar in JFrame, now there is 15 JMenus inside JMenuBar and moreover there is more than 10 JMenuItems inside every JMenus.

Now it is very tough for me to first write more than 150 lines AddMouseListener for each JMenuBar component and similarly for JMenuItem,

and the more headache increases when you have to write like evt.getSource == JMenu1 or evt.getSource == JMenuItem1,

so finally what is my requirement to get MouseListener event performed for JMenu or JMenuItem specifically,

kindly help...

ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
  • 1
    Take a look at [How to use Actions](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html), menus aren't designed to make use of MouseListeners, besides, you'd have exactly the same problems as if you used ActionListeners... – MadProgrammer Oct 22 '14 at 19:56
  • Is there any commonality among the 150+ actions taken in response to the 150+ munu items? For [example](http://stackoverflow.com/a/4039359/230513), these menu items all share a single action. – trashgod Oct 22 '14 at 19:58

1 Answers1

1

I don't have your code sample, but here's an idea of what you could do by reducing and reusing code:

JPopupMenu popup = new JPopupMenu();
popup.add(makeMenuItem("menuitem1"));

private JMenuItem makeMenuItem(String label) {
    JMenuItem item = new JMenuItem(label);
    item.addActionListener(this);
    return item;
}

In your case, just modify the codes to JMenuBar and AddMouseListener if those are your choices. As to the evt.getSource comparison, you may want to do store the MenuItems in an array and then just perform a loop of comparison.

George
  • 6,006
  • 6
  • 48
  • 68