Chapter 30. Menus and Actions

The JMenu Bar and JMenu classes in Swing work almost the same as those in the AWT. However, the JMenuItem class adds constructors that allow you to include an image alongside the menu text. To create a menu, you create a menu bar, add top-level menus, and then add menu items to each top-level menu.

    JMenuBar mbar = new JMenuBar();            //menu bar
    setJMenuBar(mbar);                         //add it to JFrame
    JMenu mFile = new JMenu("File");           //top-level menu
    mbar.add(mFile);                           //add it to the menu bar

    JMenuItem Open = new JMenuItem("Open");    //menu items
    JMenuItem Exit = new JMenuItem("Exit");
    mFile.add(Open);                           //add them to the menu

    mFile.addSeparator();                      //put in a separator
    mFile.add(Exit);

The JMenuItem object also generates an ActionEvent, and ...

Get Java™ Design Patterns: A Tutorial now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.