O'Reilly logo

Java™ Design Patterns: A Tutorial by James W. Cooper

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required