在 Eclipse RCP(Rich Client Platform)应用程序中,打开一个视图(View)通常涉及到使用命令(Command)和处理程序(Handler)。以下是一个详细的步骤指南,展示如何在 Eclipse RCP 中通过命令打开一个视图。
首先,确保你已经创建了一个新的 Eclipse RCP 项目。如果你还没有创建,可以按照以下步骤创建:
File > New > Project...
。Plug-in Project
并点击 Next
。Next
。Yes
以创建一个基于模板的 RCP 应用程序,并选择 RCP application with a view
模板。Finish
。在你的 RCP 项目中定义一个新的视图:
plugin.xml
文件。
Extensions
选项卡。
Add...
按钮并选择 org.eclipse.ui.views
扩展点。
Finish
。
org.eclipse.ui.views
扩展点并选择 New > view
。
id
、name
和 class
属性。例如:<extension point="org.eclipse.ui.views"> <view class="com.example.MyView" id="com.example.myview" name="My View"> </view> </extension>
MyView
,并使其扩展 ViewPart
:package com.example; import org.eclipse.ui.part.ViewPart; import org.eclipse.swt.widgets.Composite; public class MyView extends ViewPart { public static final String ID = "com.example.myview"; @Override public void createPartControl(Composite parent) { // Your view content goes here } @Override public void setFocus() { // Set focus to your view } }
在 plugin.xml
文件中定义一个新的命令:
Extensions
选项卡。
Add...
按钮并选择 org.eclipse.ui.commands
扩展点。
Finish
。
org.eclipse.ui.commands
扩展点并选择 New > command
。
id
和 name
属性。例如:<extension point="org.eclipse.ui.commands"> <command id="com.example.openMyView" name="Open My View"> </command> </extension>
在 plugin.xml
文件中定义一个新的处理程序:
Extensions
选项卡。
Add...
按钮并选择 org.eclipse.ui.handlers
扩展点。
Finish
。
org.eclipse.ui.handlers
扩展点并选择 New > handler
。
commandId
和 class
属性。例如:<extension point="org.eclipse.ui.handlers"> <handler class="com.example.OpenMyViewHandler" commandId="com.example.openMyView"> </handler> </extension>
OpenMyViewHandler
,并使其实现 IHandler
接口:package com.example; 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.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; public class OpenMyViewHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); try { window.getActivePage().showView(MyView.ID); } catch (Exception e) { e.printStackTrace(); } return null; } }
在 plugin.xml
文件中绑定命令到菜单或工具栏:
Extensions
选项卡。
Add...
按钮并选择 org.eclipse.ui.menus
扩展点。
Finish
。
org.eclipse.ui.menus
扩展点并选择 New > menuContribution
。
locationURI
属性。例如:<extension point="org.eclipse.ui.menus"> <menuContribution locationURI="menu:org.eclipse.ui.main.menu"> <command commandId="com.example.openMyView" label="Open My View" style="push"> </command> </menuContribution> </extension>
现在,你可以运行你的 Eclipse RCP 应用程序,并通过菜单或工具栏触发命令来打开视图。
Run As > Eclipse Application
。领取专属 10元无门槛券
手把手带您无忧上云