How to add popup menu in JFrame in netbeans visual editor

19,406

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

Share:
19,406
Ahmad Vatani
Author by

Ahmad Vatani

Senior android developer Computer science master student of Shahid Beheshti University

Updated on June 05, 2022

Comments

  • Ahmad Vatani
    Ahmad Vatani almost 2 years

    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!

  • Ahmad Vatani
    Ahmad Vatani about 10 years
    Tnx for your answer but i'm using mac and also implement my mousePressed and mouseReleased methods but not working :(
  • Ahmad Vatani
    Ahmad Vatani about 10 years
    Oooh sry :( i had a mistake. it's ok. mac popup trigger is 'mousePressed()' too :)