Eclipse4 RCP 指南

练习:添加菜单

本练习的目标

在本练习中,你将为你的应用程序建立 commands 以及 handlers,然后,你将建立菜单项来使用这些 commands。

建立 command 模型元素

打开com.example.e4.rcp.todo插件的Application.e4xmi文件,然后选择 Commands 项,这个选择在下图中高亮显示:

通过 Add... 按钮,你可以创建新的 commands,名称和 ID 是重要的字段,创建下列的 commands。

ID 名称
org.eclipse.ui.file.saveAll Save
org.eclipse.ui.file.exit Exit
com.example.e4.rcp.todo.command.new New Todo
com.example.e4.rcp.todo.command.remove Remove Todo
com.example.e4.rcp.todo.command.test For testing

建立 handler 类

为你的 handler 类创建com.example.e4.rcp.todo.handlers包。

所有的 handler 类实现通过 @Execute 注解的 execute() 方法。

package com.example.e4.rcp.todo.handlers;

import org.eclipse.e4.core.di.annotations.Execute;

public class SaveAllHandler {
  @Execute
  public void execute() {
    System.out.println((this.getClass().getSimpleName() + " called"));
  }
}

为所有的类使用这个模板,实现下列的类。

  • SaveAllHandler
  • ExitHandler
  • NewTodoHandler
  • RemoveTodoHandler
  • TestHandler

建立 Handler 模型元素

在你的应用程序模型中选择应用程序范围 Handlers 项,然后为你的 commands 创建下表中的 handlers。对于 handler 的定义,ID、command、以及 class 是相关的信息。

为所有 handlers 使用com.example.e4.rcp.todo.handler前缀。

Handler ID Command Class
.saveall Save SaveAllHandler
.exit Exit ExitHandler
.new New Todo NewTodoHandler
.remove Remove Todo RemoveTodoHandler
.test For testing TestHandler

应用程序模型编辑器显示了 command 的名称和 ID,类 URI 跟随 bundleclass:// 方案,表中仅定义了类名是为了让表格更容易阅读。例如,对于 save handler,看起来如下:

bundleclass://com.example.e4.rcp.todo/com.example.e4.rcp.todo.handlers.SaveAllHandler

添加一个菜单

Application.e4xmi文件中选择 TrimmedWindow 项,然后勾选 Main Menu 属性。

为主菜单指派 ID org.eclipse.ui.main.menu

警告:确保主菜单的 ID 是正确的,你将在后面通过其它插件用它来贡献菜单。

添加 2 个菜单,一个名称为File,另一个名称为Edit

为 File 菜单设置 ID 为org.eclipse.ui.file.menu,为 Edit 菜单设置 ID 为com.example.e4.rcp.todo.menu.edit

添加一个 Handled MenuItem 模型元素到 File 菜单,这个项应该通过 Command 属性指向 Sava command。

在 Save 菜单之后添加一个分隔符,再之后为 Exit command 添加一项。

添加所有其他 commands 到 Edit 菜单。

为 Exit 实现一个 handler

为测试你的 handler 是否可以工作,改变你的 ExitHandler 类,当选择的时候,关闭应用程序。

package com.example.e4.rcp.todo.handlers;

import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.workbench.IWorkbench;

public class ExitHandler {
  @Execute
  public void execute(IWorkbench workbench) {
    workbench.close();
  }
}

验证

验证当你选择 Save 菜单时,save handler 得到调用。

也要检查你能够通过 Exit 菜单项推出应用程序。

可能的问题:Exit 菜单项 on Mac OS

If you use the "org.eclipse.ui.file.exit" ID for your exit command, the Eclipse framework tries to map the exit command to its default menu location on the MacOS. If you don't see your exit menu, in its defined position, check this location.