如何获取调用JPopupMenu的组件?

时间:2012-09-14 08:39:23

标签: java swing jtable jpopupmenu

我有一个JPopUpMenu,我添加到多个JTables,我想获得右键单击的特定表,以便我可以对其进行更改。如何在Action Listener中获取触发JPopupMenu的组件?

JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuItemRename = new JMenuItem("Rename");
popupMenu.add(menuItemRename);
table.getTableHeader().setComponentPopupMenu(popupMenu);

ActionListener menuListener = new ActionListener() {
    public void actionPerformed(ActionEvent event) {
           String newTitle = JOptionPane.showInputDialog(null, "Enter new title");
                   //Get the table and rename it here 
                }
            };
menuItemRename.addActionListener(menuListener);

3 个答案:

答案 0 :(得分:9)

使用getInvoker()方法。

Component invoker = popupMenu.getInvoker();

答案 1 :(得分:0)

使用event.getSource()方法;

答案 2 :(得分:-1)

FWIW,

// ActionEvent e
((JPopupMenu)((JMenuItem)e.getSource()).getParent()).getInvoker()

OMG ...