MenuListener Implementation, how to detect which JMenu was clicked?

Johnydep picture Johnydep · Dec 21, 2011 · Viewed 7.7k times · Source

If I have defined JMenu and JMenuBar like this:

private JMenuBar jMenuBar;
private JMenu jMenu1;

jMenuBar = new JMenuBar();
jMenu1 = new JMenu();
jMenu1.setText("ABOUT");

//and here add a MenuListener so that i can detect when a menu is clicked:
jMenu1.addMenuListener(this);

jMenuBar.add(jMenu1);
setJMenuBar(jMenuBar);


//and here i implement the menulisteners

public void menuSelected(MenuEvent e) {
   //my logic here
}
public void menuDeselected(MenuEvent e) {}
public void menuCanceled(MenuEvent e) {}

Now it works fine. But the problem is if i have more then one menu, how can i distinguish between the two. Like in the menu listener, how would i know the click came from menu1 or another menu 2?

I mean if i have another menu and i add menu listener for this menu as well:

jMenu2.addMenuListener(this);

then i can not distinguish from which menu the click came from. How can i do that?

Answer

Harry Joy picture Harry Joy · Dec 21, 2011

You can use getSource() method of MenuEvent class. Or you can also add separate listeners to both menus as anonymous class.

public void menuSelected(MenuEvent e) {
   //Make sure jMenu1 and jMenu2 are accessible in here.
   if(e.getSource()==jMenu1)
      operationForMenu1();
   else if(e.getSource()==jMenu2)
      operationForMenu2();
}

or

   jMenu1.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent arg0) {
            // operation here.
        }

        @Override
        public void menuDeselected(MenuEvent arg0) {
        }

        @Override
        public void menuCanceled(MenuEvent arg0) {
        }
    });
    jMenu2.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent arg0) {
            // operation here.
        }

        @Override
        public void menuDeselected(MenuEvent arg0) {
        }

        @Override
        public void menuCanceled(MenuEvent arg0) {
        }
    });

If you choose second option then it will easy to use ActionListener instead of MenuListener. (Only if you do not want to do operation on menuCanceled and menuDeselected) (removed this as suggested by @Kleopatra in comment)