JPopupMenu知道点击了哪个JMenuItem

Fry*_*Fry 1 java swing jpopupmenu jmenuitem

我的问题非常简单.我有一个JPopupMenu显示两个JMenuItem.我发现知道用哪个项目点击的唯一方法

class MenuActionListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    System.out.println("Selected: " + e.getActionCommand());    
  }
}
Run Code Online (Sandbox Code Playgroud)

但该命令e.getActionCommand()打印项目内的文本.我想得到一个索引from 0 to n,知道哪个项被点击,而不是文本(可以修改).可能吗 ?

Mad*_*mer 8

你可以...

将每个JMenuItem放在a中Map,使用int您想要的值

Map<JMenuItem, Integer> menuMap = new HashMap<JMenuItem, Integer>(25);
//...
JMenuItem item1 = ...
menuMap.put(item, 0);
JMenuItem item2 = ...
menuMap.put(item, 1);
Run Code Online (Sandbox Code Playgroud)

然后在ActionListener,你只需根据事件的来源查找它...

public void actionPerformed(ActionEvent e) {
    JMenuItem item = (JMenuItem)e.getSource();
    int index = menuMap.get(item);
Run Code Online (Sandbox Code Playgroud)

你可以...

使用a 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);
Run Code Online (Sandbox Code Playgroud)

你可以...

利用ActionAPI

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"));
Run Code Online (Sandbox Code Playgroud)

你可以...

设置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");
Run Code Online (Sandbox Code Playgroud)

这个问题是你将不得不actionCommandActionEvent背面解析为int......不是一个真正完善的解决方案......

你可以...

设置clientProperty每个JMenuItem

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);
Run Code Online (Sandbox Code Playgroud)

但这变得混乱......

public void actionPerformed(ActionEvent e) {
    JMenuItem item = (JMenuItem)e.getSource();
    Object value = item.getClientProperty("keyValue");
    if (value instanceof Integer) {
        int index = ((Integer)value).intValue();
Run Code Online (Sandbox Code Playgroud)

可能还有其他解决方案,但不知道你为什么要这样做,这使得无法提出准确的建议......对不起