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);
}
});
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();
}
});
You can create a subclass as mentioned by Adir D but you can also add properties to the component itself and read those properties somewhere else. For a small number of properties or where a subclass doesn't fit, it might solve your problem.
See 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.