Java Reference
In-Depth Information
Menus
A menu is an object of the class JMenu . A choice on a menu is an object of the class JMenu-
Item . Menus are collected together in a menu bar (or menu bars). A menu bar is an object of
the class JMenuBar .
Events and listeners for menu items are handled in exactly the same way as they are for buttons.
Nested Menus
As shown in Display 17.12, the class JMenu is a descendent of the JMenuItem class. So,
every JMenu object is also a JMenuItem object. Thus, a JMenu can be a menu item in
another menu. This means that you can nest menus. For example, the outer menu
might give you a list of menus. You can display one of the menus on that list by click-
ing the name of the desired menu. You can then choose an item from that menu by
using your mouse again. There is nothing new you need to know to create these nested
menus. You simply add menus to menus just as you add other menu items. There is an
example of nested menus in the file NestedMenus.java on the accompanying CD.
extra code
on CD
The AbstractButton Class
As shown in Display 17.12, the classes JButton and JMenuItem are derived classes of the
abstract class named AbstractButton . All of the basic properties and methods of the
classes JButton and JMenuItem are inherited from the class AbstractButton . That is
why objects of the class JButton and objects of the class JMenuItem are so similar. Some
of the methods for the class AbstractButton are listed in Display 17.15. All these meth-
ods are inherited by both the class JButton and the class JMenuItem . (Some of these
methods were inherited by the class AbstractButton from the class JComponent , so you
may sometimes see some of the methods listed as “inherited from JComponent .”)
Adding Menus to a JFrame
In the following, we assume that all code is inside a constructor for a (derived class of a)
JFrame . To see the following examples put together to produce a complete GUI, see the con-
structor in Display 17.14.
Creating Menu Items
A menu item is an object of the class JMenuItem . You create a new menu item in the usual
way, as illustrated by the following example. The string in the argument position is the dis-
played text for the menu item.
JMenuItem redChoice = new JMenuItem("Red");
Search WWH ::




Custom Search