Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Add Listeners to JMenuBar

Reply
Thread Tools

Add Listeners to JMenuBar

 
 
Jason Cavett
Guest
Posts: n/a
 
      10-04-2006
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.

 
Reply With Quote
 
 
 
 
Shawn
Guest
Posts: n/a
 
      10-04-2006
Jason Cavett wrote:
> 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>
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Find all event listeners on a link, including delegated listeners? Matt Kruse Javascript 2 05-28-2010 06:28 AM
JInternalFrame and JMenuBar Big - Goofy Java 8 01-30-2007 03:57 AM
Focus Loss with JMenuBar srinivas.veeranki@gmail.com Java 0 09-21-2006 03:23 PM
JMenuBar and JPanel Ajay Java 1 09-24-2005 12:24 AM
Handle JMenuBar with visible glass pane Simon Niederberger Java 2 05-19-2004 07:15 AM



Advertisments