Igor
Igor

Reputation: 1592

How to get the component that invoked a JPopupMenu?

I have a JPopUpMenu that I added to multiple JTables and I would like to get the specific table that's right clicked so I can make changes to it. How can I get the component that triggers the JPopupMenu in the Action Listener?

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);

Upvotes: 8

Views: 3113

Answers (3)

18446744073709551615
18446744073709551615

Reputation: 16832

FWIW,

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

OMG...

Upvotes: 2

vincenzo iafelice
vincenzo iafelice

Reputation: 270

Use the event.getSource() method;

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

Use the getInvoker() method.

Component invoker = popupMenu.getInvoker();

Upvotes: 10

Related Questions