How to add popup menu in JFrame in netbeans visual editor

Ahmad Vatani picture Ahmad Vatani · Apr 30, 2014 · Viewed 18.9k times · Source

I already try to add PopUp menu to JFrame by design in Netbeans visual editor, but it don't work. Can anybody step by step hint me how to add it?? Thanks a lots!

Answer

Paul Samsotha picture Paul Samsotha · Apr 30, 2014

The problem is a JPopupMenu is not a component that is initially visible or added to a container. So by just dragging and dropping it into the design view frame, will have no affect visually to the design view.

But, if you look at the source code or the navigator, you will see the jPopupMenu declared as a class member and instantiated in the initComponents() method.

I've attempted different things myself, and from what I've tried, it doesn't look like you can design the popup menu in a visual way. You can though, use the Navigator to design it.

enter image description here

  1. From the Navigator, you will see the jPopupMenu1. You can add JMenus or JMenuItems by right-clicking it and selecting Add from Palette.
  2. You can then add listener to the JMenuItem by right clicking the JMenuItem from the navigator and slecting Events -> Actions -> actionPerformed

To make the JPopupMenu appear, you need to add a MouseListener to a component, whether it's the frame or another component. For example (to the frame):

  1. Select the frame from the Navigator and right-click it and select Events -> Mouse -> and you will need to implement both mousePressed and mouseReleased, as different platforms have different popup triggers, Windows being mouseReleased and I think Mac is mousePressed (don't quote me).
  2. Create a method to show the popup menu.

    private void showPopupMenu(MouseEvent e) {
       jPopupMenu1.show(this, e.getX(), e.getY());
    }
    
  3. Implement your mousePressed and mouseReleased methods

    private void formMousePressed(MouseEvent evt) {                                  
        if (evt.isPopupTrigger()) {
            showPopupMenu(evt);
        }
    }                                 
    
    private void formMouseReleased(MouseEvent evt) {                                   
        if (evt.isPopupTrigger()) {
            showPopupMenu(evt);
        }
    } 
    

enter image description here