JDK 1.1 offers a cleaner, more self-contained method of extending the Menu class
By now you are probably well acquainted with the concept of regular and cascaded menus (see John Mitchellโs previous Java Tip, โCascading Menusโ). You are also probably aware of the fact that extending Menu class in order to provide some additional functionality was not a clean and self-contained process in the pre-1.1 Inheritance Event Model, in which all events generated by MenuItem objects had to be intercepted in the containing Frame object.
The new Delegation Event Model provides the programmer a much cleaner and robust event handling interface.
The MutuallyExclusiveMenu class is a good example of how to utilize the new Source-to-Listener event delivery mechanisms. The following scenario puts this class to use.
Letโs say we want to have a pull-down menu with several menu items โ options that the user can select. We want to impose several restrictions on the functionality of this menu:
- Only
CheckboxMenuItemscan be added to this menu. - Only one item/option can be selected/checked at a time. At the beginning, all options can be inactive/unchecked.
- If an already active item is selected, it remains active and no event is generated.
- If a non-active item is selected, the currently active/checked item must be unactivated/unchecked, and the non-active item becomes the new active/checked item. When this happens, we want to generate an
ItemEvent. - We want to be able to add an
ItemListenerto this menu class, so those who want to be notified when the selection of items in the menu changes can simply register for such notification. We want to handle all events generated by individual menu items inside our
MutuallyExclusiveMenuclass.Note: We can accomplish this only through the use of the new event handling mechanism.
CheckboxMenuItemgeneratesItemEventupon selection, so in order to intercept it, ourMutuallyExcusiveMenuhas to implement theItemListenerinterface and register itself with each member item.
Here is the code for the MutuallyExclusiveMenu class.
Here is the code for the TestApplet applet. Itโs pretty basic: All it does is create and then display our test Frame.
Here is the code for the
MutuallyExclusiveFrame subclass of Frame. It simply creates a new MutuallyExclusiveMenu and shows the text indicating which option in the menu is currently selected.
The MutuallyExclusiveMenu class is an alternative to a Panel with a bunch of mutually exclusive radio buttons. Sometimes it is not desirable to create and show an entire Panel with such buttons first in order to allow some option setting and then act upon that selection. This is when our class comes in handy. At the time this information was put together, none of the popular browsers fully supported the 1.1 release of the JDK, so if the little window with a test menu didnโt pop up when you loaded this article, you probably have to download and run it in a 1.1-friendly appletviewer.
Enjoy!


