Adding a submenu

Daniel D picture Daniel D · May 2, 2015 · Viewed 13.7k times · Source

So I tried to look at the Java docs for help for this but got confused pretty quickly. I am trying to add a submenu to the menu item 'Edit' which will have submenus Copy and Paste, and I'm note sure how to do it. I have a submenu variable created, do I use that? Please help, thank you. Code is below.

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

public class MyJFrame extends JFrame
{
JMenuBar menubar;
JMenu menu, submenu;
JMenuItem mi;

public MyJFrame(String title)
{
    super(title);
    menubar = new JMenuBar();
    setJMenuBar(menubar);
    buildMenu();
}

void buildMenu()
{
menu = new JMenu("File");

           mi = new JMenuItem("New");
           menu.add(mi);
           menubar.add(menu);

           mi = new JMenuItem("List Files");
           menu.add(mi);
           menubar.add(menu);
           menu.addSeparator();

           mi = new JMenuItem("Save As");
           menu.add(mi);
           menubar.add(menu);
           menu.addSeparator();

           mi = new JMenuItem("Close");
           menu.add(mi);
           menubar.add(menu);

    menu = new JMenu("Tools");

           mi = new JMenuItem("Sort");
           menu.add(mi);
           menubar.add(menu);

           mi = new JMenuItem("Search");
           menu.add(mi);
           menubar.add(menu);

           mi = new JMenuItem("Edit");
           menu.add(mi);
           menubar.add(menu);
           mi = new JMenuItem("Copy");
           menu.add(mi);
           menubar.add(menu);
           mi = new JMenuItem("Paste");
           menu.add(mi);
           menubar.add(menu);
}
}

Answer

Sharad Ag. picture Sharad Ag. · May 2, 2015

create a Menu instead of a MenuItem for Edit, and add MenuItems Copy and Paste. Then Add edit menu to Tools Menu .

   menu = new JMenu("Tools");

       mi = new JMenuItem("Sort");
       menu.add(mi);
       mi = new JMenuItem("Search");
       menu.add(mi);
      JMenu med = new JMenu("Edit");
        mi = new JMenuItem("Copy");
       med.add(mi);
        mi = new JMenuItem("Paste");
       med.add(mi);
       menu.add(med);
     menubar.add(menu);

Note: I have edited the last part of your code. Just replace the code from tools menu to this and try this. If it gets error, tell me.