Java Reference
In-Depth Information
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 clicking
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. 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 website.
extra code
on website
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 methods 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
constructor in Display 17.14.
Creating Menu Items
A menu item is an object of the class JMenuItem . Create a new menu item in the usual
way, as illustrated by the following example. The string in the argument position is the
displayed text for the menu item.
JMenuItem redChoice = new JMenuItem("Red");
Adding Menu Item Listeners
Events and listeners for menu items are handled in the exact same way as they are
for buttons: Menu items fire action events that are received by objects of the class
ActionListener.
SYNTAX
JMenu_Item_Name .addActionListener( Action_Listener );
 
Search WWH ::




Custom Search