Hi Everyone,

I have a project that requires to use mouse right click. Upon right click, it should display a list of categories(drop down). How Do I do I use right click?

Many thanks,

Petra

  • add MouseListener to container (JPanel???)

  • override public void mouseClicked(MouseEvent e) { then there are two ways

    panel.addMouseListener(new MouseAdapter() {
    
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getModifiers() == MouseEvent.BUTTON3_MASK && e.getClickCount() == 1) {
                // whatever
            }
        }
    });
    

    or

        panel.addMouseListener(new MouseAdapter() {
    
            @Override
            public void mouseClicked(MouseEvent e) {
                 if (SwingUtilities.isRightMouseButton(e) && e.getClickCount() == 1) {
                    // whatever
                }
            }
        });
    

i think you have to use mouseadapter class and then you have to use mouseclicked event to handle right click of mouse.

Here's a small example. You can use the getButton() function from MouseEvent.

final JLabel lblRightClickMe = new JLabel("Right click me");        //create a label
lblRightClickMe.setBounds(152, 119, 94, 14);
final JPopupMenu jpm = new JPopupMenu("Hello");                     //create a JPopupMenu
jpm.add("Right");jpm.add("Clicked");jpm.add("On");                  //add some elements
jpm.add("This");jpm.add("Label");
lblRightClickMe.setComponentPopupMenu(jpm);                         //set jpm as this label's popup menu

lblRightClickMe.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent arg0) { 
        if (arg0.getButton() == MouseEvent.BUTTON3){                //get the mouse button
            jpm.show(arg0.getComponent(), arg0.getX(), arg0.getY());//set the position and show the popup menu
        }
    }
});

Edited 3 Years Ago by Lucaci Andrew

My popup menu works now. My standard menu as well. But when I switch from standard JMenu to JPopupMenu, it doesnt display my pop up menu. How? Many thanks.

This article has been dead for over six months. Start a new discussion instead.