Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

Add Listeners to JMenuBar

Thread view: 
Jason Cavett - 04 Oct 2006 20:01 GMT
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.
Shawn - 04 Oct 2006 20:18 GMT
> Hello,
>
[quoted text clipped - 7 lines]
>
> 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>


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.