Adding a submenu in swing

... by Bittle in Programming Help October 21, 2018

Problem:

Create a submenu for a menu bar like shown below

Solution:

Adding a submenu to a menu bar can be achieved by first creating another JMenu, adding MenuItems to it, and then adding that JMenu to the main JMenu. In this case, We are going to create a JMenu for Find, and add "Find" and "replace" as JMenuItems of find. We are then going to add the Find JMenu to the edit menu item, like so:

JMenuBar menuBar=new JMenuBar();
frame.setJMenuBar(menuBar);
// add other menu items here
JMenu editMenuItem=new JMenu("Edit");

menuBar.add(editMenuItem);

//EditMenu Items
JMenuItem copyMenuItem=new JMenuItem("Copy");
JMenuItem pasteMenuItem=new JMenuItem("Paste");

JSeparator separator2=new JSeparator();

// submenu for find (will stay open on hover)
JMenu findMenuItem = new JMenu("Find");

JMenuItem mi = new JMenuItem("Find");
findMenuItem.add(mi);
mi = new JMenuItem("Replace");
findMenuItem.add(mi);
editMenuItem.add(findMenuItem);
        
// add menus here
editMenuItem.add(findMenuItem);

Comments (0)

Search Here