javaswingmenuright-clickjpopupmenu

How To Create a Pop Up Menu with Sub Menu in Java


I would like to add right click menu for my program. I added basit menu with the following code:

            Pmenu = new JPopupMenu("Menu");
            menuItem = new JMenuItem("Sections");
            Pmenu.add(menuItem);
            menuItem = new JMenuItem("Numbers");
            Pmenu.add(menuItem);

However I want to add submenu to these menus, such as user hover the Sections menu, submenu will open and sections are shown.


Solution

  • First, an Object name usually starts with a small letter, caps letters are usually used for class/interface names.

    For your question, here is the code for submenus

    //parent menu
    JPopupMenu pmenu = new JPopupMenu("Menu");
    
    //sub menu
    JMenu sectionsMenu = new JMenu("Sections");
    JMenuItem menuItem1 = new JMenuItem("Item1");
    sectionsMenu .add(menuItem1 );
    JMenuItem menuItem2 = new JMenuItem("Item2");
    sectionsMenu .add(menuItem2 );
    
    pmenu.add(sectionsMenu);
    
    //regular menu item
    menuItem = new JMenuItem("Numbers");
    pmenu.add(menuItem);
    

    JMenu tutorial or submenu examble