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.
With an instance of JMenu you can't add an ActionListener, only with JMenuItem you can do it. We can add an ActionListener to JMenu , but it just doesn't have any effect. JMenu opens its child JMenu s and JMenuItem s when the mouse hovers over it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With