如何向 JMenuItem 添加标签?

How do I add a tag to JMenuItem?

如何为我的菜单项设置标签,以便稍后在回调中使用它?

像这样。有人做过吗?

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

您可以创建 Adir D 提到的子类,但您也可以向组件本身添加属性并在其他地方读取这些属性。对于少量属性或子类不适合的地方,它可能会解决您的问题。

https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html

putClientProperty

public final void putClientProperty(Object key, Object value)

Adds an arbitrary key/value "client property" to this component.

The get/putClientProperty methods provide access to a small per-instance hashtable. Callers can use get/putClientProperty to annotate components that were created by another module. For example, a layout manager might store per child constraints this way. For example:

 componentA.putClientProperty("to the left of", componentB);

If value is null this method will remove the property. Changes to client properties are reported with PropertyChange events. The name of the property (for the sake of PropertyChange events) is key.toString().

The clientProperty dictionary is not intended to support large scale extensions to JComponent nor should be it considered an alternative to subclassing when designing a new component.

Parameters:

key - the new client property key

value - the new client property value; if null this method will remove the property

See Also: getClientProperty(java.lang.Object), Container.addPropertyChangeListener(java.beans.PropertyChangeListener)

你可以使用.setName()方法来标记它

    final JMenuItem item = new JMenuItem();
    item.setName("item1");

    item.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            String tag = item.getName();
        }
    });