Eclipse扩展点实践之添加快捷菜单项(Command方式实现)

有两种方式,一种是Action的方式,另一种是Command的方式(这两种方式的区别详见:http://wiki.eclipse.org/FAQ_What_is_the_difference_between_a_command_and_an_action%3F):

我们这里采用Command的方式:

首先添加org.eclipse.ui.commands扩展:在Extension->add->org.eclipse.ui.commands.

然后,建立Command Handler(每个command扩展必须要制定一个Command Handler,这个Command Handler实际上就是一个继承了AbstractHandler实现了IHandler的类,在这个类中的execute函数就是执行具体Command的操作)。
package com.wjy.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class AddCompany extends AbstractHandler implements IHandler{

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        // TODO Auto-generated method stub
        Display display=Display.getCurrent();
        Shell shell=new Shell(display);
        MessageDialog.openInformation(
                shell,
                "PlungInClient",
                "gugugugugu");
        return null;
    }

}
接下来:在org.eclipse.ui.commands下添加command和category:new->command(command中的name就是最后显示的名称),关键是defaultHandler这一项一定要填上建立的Command Handler的路径。

再添加一个category.

最后:添加org.eclipse.ui.menus扩展,给command提供ui响应。首先添加org.eclipse.ui.menus扩展点,再new->menuContribution(这个locationURI很重要写上“popup:org.eclipse.ui.popup.any”就可以在快捷菜单总显示了,无论在哪里右键单击都会显示因为是any).

最后一步就是讲这个menu和command关联起来:在这个menuContribution上右键单击new->command就完工了。这里可以设置显示的图标。

效果如下:

点击"元元"之后的效果:

原文地址:https://www.cnblogs.com/wangjiyuan/p/plungin.html