Add Listeners to JMenuBar

J

Jason Cavett

Hello,

What is the easiest way to add an ActionListener to every JMenuItem in
a JMenuBar (asuming that the JMenuBar has already been created)?

I have a general idea - but it seems like having to recursively iterate
through every item in the menu is overkill - or is that really the only
way of doing it? (Is there a generic - "add an action listener to
every item in the menu" type method? I couldn't find anything.)


Thanks.
 
S

Shawn

Jason said:
Hello,

What is the easiest way to add an ActionListener to every JMenuItem in
a JMenuBar (asuming that the JMenuBar has already been created)?

I have a general idea - but it seems like having to recursively iterate
through every item in the menu is overkill - or is that really the only
way of doing it? (Is there a generic - "add an action listener to
every item in the menu" type method? I couldn't find anything.)


Thanks.

Good question! I would have a higher level JMenu like the following
JMenuPower. Just throw in the JMenuItem object to it and it will take
care of the rest.

//Now JMenu looks "primitive" and JMenuPower is relatively higher level
public class JMenuPower extends JMenu
{


public JMenuPower(String s)
{
super(s);
}

void addMenuItemAndListener(JMenuItem mi, ActionListener al)
{
mi.addActionListener(al);
this.add(mi);
}

}

To use it:

<code>
public class MemoGUI extends JFrame implements ActionListener
{
....

JMenuPower memoMenu = new JMenuPower("Memos"); //my own
JMenuPower class
JMenuItem m;

m = new JMenuItem("JMenuItem1");
memoMenu.addMenuItemAndListener(m, this);

m = new JMenuItem("JMenuItem2");
memoMenu.addMenuItemAndListener(m, this);

</code>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top