Search code examples
javaswingright-clickjcomponentjpopupmenu

JPopupMenuItem get component that triggered the JPopupMenu


I have got a JRadioButton and set a ComponentPopupMenu to it.

JRadioButton rdbtnTest = new JRadioButton();
rdbtnTest.setComponentPopupMenu(popupMenu);

The popupMenu is a JPopupMenu with one JPopupMenuItem. The JPopupMenuItem has a MouseListener, so that on a mouse click, a webpage is opened.

JPopupMenu popupMenu = new JPopupMenu("GO");
PopupMenuListener popupMenuListener = new MyPopupMenuListener();
popupMenu.addPopupMenuListener(popupMenuListener);
MenuItem openMenuItem = new JMenuItem("Open Webpage");

openMenuItem.addMouseListener(new MouseListener() {
        @Override
        public void mousePressed(MouseEvent arg0) {
            Component comp = arg0.getComponent(); // will only return the JPopupMenuItem
            // Determine the right-clicked radio button and open webpage
        }
popupMenu.add(openMenuItem);

My question is: if I have another JRadioButton rdbtnTest2 with the same popupMenu, can I determine which of the two radio buttons triggered the JPopupMenu? When opening the webpage, I need to pass a specific parameter according to which radio button was right-clicked.


Solution

  • Whn you show popup menu in a MouseListener just get event source and store it somewhere (radiobutton which calls the menu). In your code just check the popup invoker.