2

Here is the minimal working application :

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class JMenuItemReuse {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TestFrame::new);
    }
}

class TestFrame extends JFrame {

    public TestFrame() {
        super();

        JPanel panel = new JPanel();

        JPopupMenu menu1 = new JPopupMenu();
        JPopupMenu menu2 = new JPopupMenu();
        JMenuItem item1 = new JMenuItem("reused");
        JMenuItem item2 = new JMenuItem("not reused");

        menu1.add(item1);
        menu2.add(item1); // works if this line is commented
        menu2.add(item2);

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (SwingUtilities.isRightMouseButton(e)) {
                    menu1.show(panel, e.getX(), e.getY());
                } else {
                    menu2.show(panel, e.getX(), e.getY());
                }
            }
        });
        panel.add(new JLabel("popup-test"));
        add(panel);

        setPreferredSize(new Dimension(400, 400));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
}

The problem is that the popup menus do not work as expected when at least one menu item is reused. It is not a big issue, can be easily avoided by duplicating the reused menu item, but I am still wondering why does it happen. Any ideas?

Bogdan A.
  • 65
  • 1
  • 8

1 Answers1

1

A JMenuItem belongs to one, and only one, JPopupMenu (or any other menu). You cannot add a Swing component to more than one container; if you do, then the component will automatically be removed from the previous container. Actaully if you want, you can create Actions. Actions can be shared and added to multiple components (JMenuItems, JButtons etc). You can even enable/disable the Action which will enable/disable all the components at the same time.

bhavna garg
  • 270
  • 2
  • 19