有不少朋友问到如何把一个已有的Eclipse插件转换为RCP应用程序,其实这个 过程并不复杂,因为RCP应用也是基于插件的结构,可以说RCP 就是精简后的 Eclipse平台,只是我们要对这个平台做一些定制工作。将任何一个传统的 Eclipse插件项目转换到RCP可以分为两个步骤,这篇先介绍第一个步骤:建立应 用程序。
在GEF入门系列(三、应用实例)里我曾做过一个精简的GEF应用程序(下载) ,这一篇里我就一步一步的把这个例子转换为RCP应用程序(点击下载转换后的项 目打包)。应用程序(Application)是通过扩展 org.eclipse.core.runtime.applications扩展点建立的,其作用是让Eclipse知 道你的RCP需要什么样的功能,比如界面上有哪些视图,菜单和工具条,应用程序 窗口的初始大小等等。在plugin.xml里添加应用程序的定义很简单,像下面这样 指定一个id和一个类名就可以了。
<extension
id="myapplication"
point="org.eclipse.core.runtime.applications">
<application>
<run class="com.example.application.MyApplication"/>
</application>
</extension>
接下来我们的主要任务是实现这个类,MyApplication必须实现 org.eclipse.core.runtime.IPlatformRunnable接口,这个接口只定义了一个 run()方法,对于Eclipse Platform来说这个方法就相当于传统java程序的main() 方法,是入口方法。所有RCP应用程序里这个方法的实现几乎是完全一样的,即启 动 Workbench,并把一个WorkbenchAdvisor实例作为参数传给它,如下所示:
public class MyApplication implements IPlatformRunnable {
public Object run(Object args) throws Exception {
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new MyWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IPlatformRunnable.EXIT_RESTART;
}
return IPlatformRunnable.EXIT_OK;
} finally {
display.dispose();
}
}
}
所以应用程序的定制实际上是通过这个WorkbenchAdvisor实例实现的。现在我 们要构造 org.eclipse.ui.application.WorkbenchAdvisor类的一个子类,也就 是上面代码里出现的 MyWorkbenchAdvisor,然后覆盖它的一些方法。比较重要的 是这两个方法:createWorkbenchWindowAdvisor() 返回一个 WorkbenchWindowAdvisor实例,从类名不难看出它的作用是定制应用程序窗口, 包括菜单和工具条,稍后将详细介绍; getInitialWindowPerspectiveId()返回 一个透视图的id字符串,这个透视图定义RCP应用程序的界面布局,所以如果在原 来的插件里你没有定义透视图,现在必须要新定义一个了。
public class MyWorkbenchAdvisor extends WorkbenchAdvisor {
private static final String PERSPECTIVE_ID = "com.example.ui.MyPerspective";
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
IWorkbenchWindowConfigurer configurer) {
return new MyWorkbenchWindowAdvisor(configurer);
}
public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
//The workaround call
WorkbenchAdapterBuilder.registerAdapters();
}
}