Eclipse 插件开发 6 右键菜单
1 plugin.xml
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<!-- 定义命令 -->
<extension point="org.eclipse.ui.commands">
<command id="HelloWorldPlugin.commands.helloCommand" name="测试">
</command>
</extension>
<!-- 定义右键菜单 -->
<extension point="org.eclipse.ui.menus">
<menuContribution locationURI="popup:org.eclipse.ui.popup.any">
<command commandId="HelloWorldPlugin.commands.helloCommand" label="测试" style="push">
</command>
</menuContribution>
</extension>
<!-- 定义命令处理器 -->
<extension point="org.eclipse.ui.handlers">
<handler class="com.xu.work04.handlers.SampleHandler" commandId="HelloWorldPlugin.commands.helloCommand">
</handler>
</extension>
</plugin>
2 SampleHandler.java
package com.xu.work04.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;
public class SampleHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation( window.getShell(), "Work04", "右击菜单弹出框!");
return null;
}
}
3 Activator.java
package com.xu.work04;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "com.xu.work04"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}