How do I create a right click context menu in Java Swing?

后端 未结 5 1394
长情又很酷
长情又很酷 2020-11-28 20:51

I\'m currently creating a right-click context menu by instantiating a new JMenu on right click and setting its location to that of the mouse\'s position... Is t

5条回答
  •  不知归路
    2020-11-28 21:13

    I will correct usage for that method that @BullyWillPlaza suggested. Reason is that when I try to add add textArea to only contextMenu it's not visible, and if i add it to both to contextMenu and some panel it ecounters: Different parent double association if i try to switch to Design editor.

    TexetObjcet.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)){
                    contextmenu.add(TexetObjcet);
                    contextmenu.show(TexetObjcet, 0, 0);
                }
            }
        }); 
    

    Make mouse listener like this for text object you need to have popup on. What this will do is when you right click on your text object it will then add that popup and display it. This way you don't encounter that error. Solution that @BullyWillPlaza made is very good, rich and fast to implement in your program so you should try it our see how you like it.

提交回复
热议问题