javaswingjmenujmenuitem

How do I add a tag to JMenuItem?


How can I set a tag for my menu item so that I can ue it later in the callback?

Something like this. Somebody have ever do it?

JMenuItem item = new JMenuItem(mnu.text);
item.setSomething(myTag) ???;
                    
item.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) 
   {
      start_something(myTag);
   }
});

Solution

  • You can use .setName() method for tagging it

        final JMenuItem item = new JMenuItem();
        item.setName("item1");
    
        item.addActionListener(new ActionListener() {
    
            public void actionPerformed(ActionEvent e) {
                String tag = item.getName();
            }
        });