GUI Commands 2.0 has arrived! Find out what's new and improved.
Managing Menus

Using a JMenuBar

In just about every application I write I use the following snippet to create my main menubar.

   /**
    * Create my frame and load the menu bar.
    */
   public MyFrame()
   {
      // load the mainMenuGroup
      mainMenuGroup = CommandManager.defaultInstance().getGroup("main-menu");
      
      // ..and install the menu bar
      setJMenuBar(mainMenuGroup.createMenuBar());
      
   }

The great advantage of this is that the commands can be instantiated where they belong, not where the menu is built. It's also very simple.

Making the menu dynamic

The following method is taken from the main frame class in the demo (web start) and is invoked to install a given example's menu into the main frame. It simply resets the main menu group back to it's original state and adds the example's menu. You can also remove individual group members using CommandGroup.remove(...) instead of reset.

   /**
    * Loads the specified group into the main menu.  
    * @param menu the {@link CommandGroup} to be installed into the main menu.
    */
   public void
   installMenu(CommandGroup menu)
   {
      // reset the main menu back to its default members
      mainMenuGroup.reset();

      // and add the new menu
      mainMenuGroup.add(menu);
   }

Taking it further

The obvious next step is handle multiple menus that can be embedded within the main menu structure. This takes a little more work but is still pretty easy.

The MatchVisitor will search the a given groups immediate children to find a match based on the text of a given face. If an existing matching menu is found, the new menu will be added to it (at it's expansion point).

    /**
    * Installs the specified menu into the main menu.  If the menu has the same 
    * text as an existing menu it will be added inline to that menu.
    * @param menu the {@link CommandGroup} to be installed into the main menu.
    */
   private void installMenu(CommandGroup menu)
   {
      // reset all the menus back to their default state
      mainMenuGroup.visit(new ResetVisitor(ResetVisitor.SHALLOW));
      
      // try and find an existing menu that has the same name as
      // the menu being added
      MatchVisitor visitor = new MatchVisitor(menu, Face.MENU, MatchVisitor.SHALLOW);
      mainMenuGroup.visit(visitor);
      
      // if we found one, add the menu to it, otherwise add it to the main menu
      if (visitor.foundMatch())
         visitor.getMatchingGroup().addInline(menu);
      else
         mainMenuGroup.add(menu);
   }