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?
That is what
getSource()
is for, which is a methodMenuEvent
inherits fromEventObject
.You can use
getSource()
method of MenuEvent class. Or you can also add separate listeners to both menus as anonymous class.or
If you choose second option then it will easy to use(removed this as suggested by @Kleopatra in comment)ActionListener
instead ofMenuListener
. (Only if you do not want to do operation on menuCanceled and menuDeselected)Change the colour of the button or label. simple and short xoxo
I came here to see if there was anything I preferred to getSource(), and decided to stick with getSource. It's my preference to work with strings (vs comparing objects), so I'm posting my code in case it's helpful to anyone. (I know some people don't like early returns, don't like switch statements, don't like K&R. Again, personal preference, adapt as desired.)
Naturally, JMenu(s) that don't addMenuListener() don't even trigger menuSelected().
You can use
ActionListener
instead. Here is how you can capture a click on a menu itemIf you have more than one menu sharing the same bit of code when clicked then you can refactor the action listener into a separate class.
I think that one of ways is add
ButtonModel
toJMenuItem
or addJMenuItems
to theButtonGroup
can solve confortly that too, example for ButtonModel