-->

Eclipse E4 - Menu contribution and PersistedState

2019-08-29 20:12发布

问题:

I have got ditched in a problem with Menu Contribution and PersistedState. I had no problem before removing the -clearPersistedState flag from the VM args.

Now, the app has a weird behaviour, the menu contribution starts to pile up a menu entry every time the code is executed.

Here it's the guilty snippet enclosed in a Processor:

MDirectMenuItem menuItem = MMenuFactory.INSTANCE.createDirectMenuItem();
    menuItem.setLabel("Another Exit");
    menuItem.setContributionURI("bundleclass://"
            + "com.telespazio.optsat.wizard/"
            + ExitHandlerWithCheck.class.getName());
    if (!menu.getChildren().contains(menuItem))
        menu.getChildren().add(menuItem);

回答1:

The menu items you add to the application model will be persisted, so you need to check if they already exist in the menu. The contains check you currently have does not do this.

You need to check for a match of the label (or the contribution URI, or the id), something like:

List<MMenuElement> children = menu.getChildren();

boolean gotExisting = false;

for (MMenuElement child : children)
 {
   if ("Another Exit".equals(child.getLabel())
    {
      gotExisting = true;
      break;
    }
 }

if (!gotExisting)
 {
   ... add to menu
 }