Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

FAQ How do I make menus with dynamic contents?

Revision as of 16:27, 14 March 2006 by Claffra (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

By default, menu managers in JFace are static; that is, contributions are added once when the view is created, and they remain unchanged each time the view is opened. Individual actions may enable or disable themselves, based on the current context, but the menu itself remains stable.


If you want the contents of your menus to change every time the menu is opened, you should make your menu manager dynamic. When the menu manager is created, make it dynamic by calling setRemoveAllWhenShown:

   IMenuManager menu = new MenuManager("Name");
   menu.setRemoveAllWhenShown(true);

By setting this flag, the menu manager will remove all actions and submenus from the menu every time the menu is about to be shown. Next, you need to install on the menu a listener that will add your actions:

   IMenuListener listener = new IMenuListener() {
      public void menuAboutToShow(IMenuManager m) {
      if (daytime) {
         m.add(workAction);
         m.add(playAction);
      } else {
         m.add(sleepAction);
      }
   };
   menu.addMenuListener(listener);

This menu will now have different actions, depending on the value of the daytime variable.

It is possible to make a menu that is partially dynamic, with some actions added at creation time and some actions added or removed by a menu listener when the menu is opened. However, it is generally not worth the added complexity. Note that even for dynamically contributed actions, you should retain the same action instances and recontribute them each time the menu opens. Creating action instances from scratch every time the menu opens is not generally a good idea as actions often install themselves as listeners or perform other nontrival initialization.


This FAQ was originally published in Official Eclipse 3.0 FAQs. Copyright 2004, Pearson Education, Inc. All rights reserved. This text is made available here under the terms of the Eclipse Public License v1.0.

Back to the top