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

CanCeylan picture CanCeylan · Oct 5, 2011 · Viewed 21.1k times · Source

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.

Answer

Adi Mor picture Adi Mor · Oct 5, 2011

First Object name usually start with a small letter, caps letter usually used for class/interface names.

for your question, there is the code for submenu

//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