你可以...
将每个JMenuItem 放在Map 中,并使用您想要的int 值
Map<JMenuItem, Integer> menuMap = new HashMap<JMenuItem, Integer>(25);
//...
JMenuItem item1 = ...
menuMap.put(item, 0);
JMenuItem item2 = ...
menuMap.put(item, 1);
然后在ActionListener中,您只需根据事件来源查找它...
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem)e.getSource();
int index = menuMap.get(item);
你可以...
使用List 并确定列表中JMenuItem 的索引...
List<JMenuItem> menuList = new ArrayList<JMenuItem>(25);
//...
JMenuItem item1 = ...
menuList.add(item);
JMenuItem item2 = ...
menuList.add(item);
//...
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem)e.getSource();
int index = menuList.indexOf(item);
你可以...
利用Action API
public class IndexedAction extends AbstractAction {
private int index;
public IndexedAction(int index, String name) {
this.index = index;
putValue(NAME, name);
}
@Override
public void actionPerformed(ActionEvent e) {
// Use the index some how...
}
}
//...
JPopupMenu menu = new JPopupMenu();
menu.add(new IndexedAction(0, "Item 1"));
menu.add(new IndexedAction(1, "Item 2"));
menu.addSeparator();
menu.add(new IndexedAction(2, "Item 3"));
menu.add(new IndexedAction(3, "Item 4"));
你可以...
设置项目的actionCommand属性...
JPopupMenu pm = ...;
pm.add("Item 1").setActionCommand("0");
pm.add("Item 2").setActionCommand("1");
menu.addSeparator();
pm.add("Item 3").setActionCommand("2");
pm.add("Item 4").setActionCommand("3");
问题在于您必须将ActionEvent 的actionCommand 解析回int...不是真正的隔音解决方案...
你可以...
设置每个JMenuItem的clientProperty
JPopupMenu pm = ...;
pm.add("Item 1").putClientProperty("keyValue", 0);
pm.add("Item 2").putClientProperty("keyValue", 1);
menu.addSeparator();
pm.add("Item 3").putClientProperty("keyValue", 2);
pm.add("Item 4").putClientProperty("keyValue", 3);
但这会变得一团糟……
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem)e.getSource();
Object value = item.getClientProperty("keyValue");
if (value instanceof Integer) {
int index = ((Integer)value).intValue();
可能还有其他解决方案,但不知道您为什么要这样做,因此无法提出准确的建议......对不起