Pavithra Gunasekara
Pavithra Gunasekara

Reputation: 4112

JPopupMenu is not working

I wrote a simple program to understand how JPopupMenu works. But something is wrong with my code it doesn't show popup menu correctly. Please can someone tell me the reason?

public class PopUpMenu extends JFrame implements ActionListener {

JPanel panel;
JPopupMenu popMenu;
JMenuItem cut;
JMenuItem copy;

public PopUpMenu() {

    setVisible(true);
    setSize(300, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    panel = new JPanel();
    popMenu = new JPopupMenu();
    cut = new JMenuItem();
    popMenu.add(cut);
    copy = new JMenuItem();
    popMenu.add(copy);

    add(panel);
    panel.setComponentPopupMenu(popMenu);

    addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent Me) {
            if (Me.isPopupTrigger()) {
                popMenu.show(Me.getComponent(), Me.getX(), Me.getY());
            }
        }
    });

}

public void actionPerformed(ActionEvent arg0) {

}

public static void main(String[] args) {

    Runnable r = new Runnable() {
        public void run() {
            PopUpMenu pop = new PopUpMenu();
        }
    };
    SwingUtilities.invokeLater(r);

}

}

Upvotes: 0

Views: 1451

Answers (2)

Mohamed Saligh
Mohamed Saligh

Reputation: 12349

Your MenuItem size is 0 that is the reason I guess.

So, set some text for your MenuItem.

cut = new JMenuItem("Cut");
...
copy = new JMenuItem("Copy");

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692191

Your code is perfectible (the mouse listener is not needed, and the panel should be added to the content pane of the JFrame), but it works. Maybe it would seem to work better if you gave some text to your menu items :

cut = new JMenuItem("Cut");

Upvotes: 4

Related Questions