Question

How can I handle adding JMenuItem (newItem) to the JMenu (menuUsers)? Is there a proper ActionListener for this purpose? There is a part of code that performs adding menu items to menu. It performs when some event is raised. Here it is:

public void UpdateUserList(Map<String, UserSchedule> allSchedule) throws Exception {
    menuUsers.removeAll();
    Iterator it = allSchedule.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        JMenuItem newItem = new JMenuItem(entry.getKey().toString());
        newItem.setName("User");
        menuUsers.add(newItem);
    }
}

I'd like to be like this (pseudo-code):

menuUsers.addSomeListener(new SomeListener()
{
    void performWhenNewItemAdded(...) {
      ...
    }
}
Was it helpful?

Solution

"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 ActionListeners at all. Just add the Action to the JMenu. See more at How to use Actions

enter image description here


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.
     }
 });

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top