Question

I would line to get the reference of selected menu item of the menu. How can I do this?

This is an example of a class which is responsible for execute the marked by @Execute annotation method.

This is a wrong way:

import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;

import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.MElementContainer;
import org.eclipse.e4.ui.model.application.ui.MUIElement;
import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
import org.eclipse.e4.ui.model.application.ui.menu.MMenu;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuElement;

import com.lwm.app.parts.GuiContainer;

public final class MenuItemSelectionExecution {


    @SuppressWarnings("rawtypes")
    private MElementContainer menu = null;

    @Inject
    private MWindow window;

    @CanExecute
    public boolean canExecute() {

        if (null == menu) {
            setMenu();
        }

        if (null == menu) {
            return false;
        }
        return true;
    }



    @Execute
    public void execute(MApplication app) {


        MWindow selectedElement = app.getSelectedElement();
        System.out.println(selectedElement);

        MUIElement selectedElement2 = menu.getSelectedElement();
        //selectedElement2 = null


    }

    @SuppressWarnings("rawtypes")
    private void setMenu() {
        final MMenu mainMenu = window.getMainMenu();
        final List<MMenuElement> mainMenuItems = mainMenu.getChildren();
        final Iterator<MMenuElement> iterator = mainMenuItems.iterator();

        MMenuElement currentMainMenuItem = null;
        String label = null;
        MElementContainer menu = null;

        while (iterator.hasNext()) {
            currentMainMenuItem = iterator.next();
            label = currentMainMenuItem.getLabel();
            if (currentMainMenuItem instanceof MElementContainer) {
                menu = (MElementContainer) currentMainMenuItem;
                if (GuiContainer.PROGRAMS.equals(label)) {
                    this.menu = menu;
                    break;
                }
            }
        }

    }
}

I hope someone help me to know right way.

Was it helpful?

Solution

You should just be able to inject the MMenuItem on the method:

@CanExecute
public boolean canExecute(@Optional MMenuItem menuItem);

If the handler is not called from a menu the @Optional will mean the call will still work and the menu item will be null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top