"How can I handle adding JMenuItem (newItem) to the menu (menuUsers)?"
For JmenuItems
I would use an Action
istead. You can add images, text, tooltips, and key bindings to them. Also they can be reused by other components. See this answer for a couple examples.
Here's a screenshot if what can be accomplished. You don't need any JMenuItems
or ActionListener
s at all. Just add the Action
to the JMenu
. See more at How to use Actions
To answer the question more directly...
"Is there a proper ActionListener for this purpes?"
You are doing it wrong. You appear to be trying to add an ActionListener
to the JMenu
. Instead the ActionListener
should be added to the JMenuItem
. See more at How to use Menus
jMenuItem.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
If for some reason you did want to add a listener to the JMenu
and not the JMenuItem
, you should use a MenuListener
that listens foe MenuEvents
, where the following are the only three methods you can override. There is no method for when an JMenuItem
is added.
userMenu.addMenuListener(new MenuListener(){
@Override
public void menuCanceled(MenuEvent e) {
// Invoked when the menu is canceled.
}
@Override
public void menuDeselected(MenuEvent e) {
// Invoked when the menu is deselected.
}
@Override
public void menuSelected(MenuEvent e)
// Invoked when a menu is selected.
}
});