8

我有一个添加到多个 JTable 的 JPopUpMenu,我想获得右键单击的特定表,以便对其进行更改。如何在 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);
4

3 回答 3

10

使用getInvoker()方法。

Component invoker = popupMenu.getInvoker();
于 2012-09-14T08:43:15.120 回答
0

使用event.getSource()方法;

于 2012-09-14T08:50:46.023 回答
0

FWIW,

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

我的天啊...

于 2020-03-11T23:05:42.010 回答