JHotDraw Pattern Language

Creating Custom Menus

A menu in JHotDraw

Menus reside on the menu bar that exists at the top of the application window. Menus are comprised of menu items and sets of items are generally grouped by functionality. In JHotDraw the default menu bar contains menus for File, Edit, Align, Attributes and Debug operations.

The DrawApplication class defines the application's menus. Subclasses may alter, remove (with caution) or add menus (and their menu items) to reflect the requirements of the application. Menus and menu items and the menu bar are constructed using Java's standard components (Menu, MenuItem and MenuBar).

DrawApplication uses the Factory Method design pattern to localise menu creation into separate methods (i.e. to create the ‘New’ menu item on the File menu the code below is used). The same technique should be used when creating new menus in an application.

(NB The behaviour of the menu item is encapsulated in the ActionListener class (which in this case calls the DrawApplications promptNew() method and the menu that is returned by the createFileMenu() method is added to the MenuBar in the createMenus(MenuBar mb) method).

     protected Menu createFileMenu() {
         Menu menu = new Menu("File");
         MenuItem mi = new MenuItem("New", new MenuShortcut('n'));

                new ActionListener() {    
                    public void actionPerformed(ActionEvent event) { promptNew(); } 


         … above is repeated for all other menu items on the file menu
     } // end of createFileMenu()

Some menus are context sensitive and should only be activated when the correct type of figure has been selected. In such a case changes to the selection behaviour must be made to ensure that that menu (or menu item) only becomes available at the correct times. (This is the reason why caution must be used when removing menu items as the selection behaviour assumes certain menus exist when setting which menus are active.)

Copyright Douglas Kirk