Add Listeners to JMenuBar

Discussion in 'Java' started by Jason Cavett, Oct 4, 2006.

  1. Jason Cavett

    Jason Cavett Guest

    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.
     
    Jason Cavett, Oct 4, 2006
    #1
    1. Advertising

  2. Jason Cavett

    Shawn Guest

    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>
     
    Shawn, Oct 4, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Simon Niederberger

    Handle JMenuBar with visible glass pane

    Simon Niederberger, May 18, 2004, in forum: Java
    Replies:
    2
    Views:
    1,073
  2. Ajay

    JMenuBar and JPanel

    Ajay, Sep 23, 2005, in forum: Java
    Replies:
    1
    Views:
    15,846
  3. Replies:
    0
    Views:
    405
  4. Big - Goofy

    JInternalFrame and JMenuBar

    Big - Goofy, Jan 28, 2007, in forum: Java
    Replies:
    8
    Views:
    1,143
    Andrew Thompson
    Jan 30, 2007
  5. Matt Kruse
    Replies:
    2
    Views:
    182
Loading...

Share This Page