[英]How to get an IHandlerService object in Eclipse 4 RCP?
我正在做一個測試項目,並遵循了Vogella的RCP教程 。 之后,我對其進行了一些更改,例如。 創建了一個JFace
TreeView
。 現在,我希望如果用戶雙擊TreeView
元素,它將打開另一個Part
。 我有命令,但是,我不知道如何調用它。 如果您看一下該教程,您可能會注意到它僅使用部件而不使用視圖,並且我沒有啟動工作台的Application.java
類。 因此,以下方法對我不起作用:
IHandlerService handlerService = (IHandlerService) viewer.getSite().getService(IHandlerService.class);
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IHandlerService handlerService = (IHandlerService)window.getService(IHandlerService.class);
handlerService.executeCommand(cmdID, null);
他們兩個都給了我NullPointerException
。
根據Lars Vogel的說法,推薦的方法是注入服務,如下圖所示(這對我有用)。 唯一的問題是,根據插件規則,似乎無法訪問org.eclipse.e4.core.command包(可能尚未導出)。
但這有效:
import org.eclipse.e4.core.commands.ECommandService;
import org.eclipse.e4.core.commands.EHandlerService;
public class MyPart{
public static final String S_CMD_MY_COMMAND_ID = "my.command";
@Inject ECommandService commandService;
@Inject EHandlerService service;
@PostConstruct
public void createComposite(Composite parent) {
parent.setLayout(new GridLayout(2, false));
....
Button btnMyButton = new Button(parent, SWT.NONE);
btnMyButton.addSelectionListener(new SelectionAdapter() {
@SuppressWarnings({ "restriction" })
@Override
public void widgetSelected(SelectionEvent e) {
try {
Command command = commandService.getCommand( S_CMD_MY_COMMAND_ID );
if( !command.isDefined() )
return;
ParameterizedCommand myCommand = commandService.createCommand(S_CMD_MY_COMMAND_ID, null);
service.activateHandler(S_CMD_MY_COMMAND_ID, new MyCommandHandler());
if( !service.canExecute(myCommand ))
return;
service.executeHandler( myCommand );
} catch (Exception ex) {
throw new RuntimeException("command with id \"my command id\" not found");
}
}
});
....
}
該處理程序將按以下方式實現(不包括在相應的命令插件擴展中,除非您還希望它實現IDefaultHandler以實現兼容性):
public class MyCommandHandler{
@Execute
public Object execute() throws ExecutionException {
System.out.println("Hello");
return null;
}
@CanExecute
public boolean canExecute() {
return true;
}
}
有關詳細信息,請參見: http : //www.vogella.com/articles/Eclipse4Services/article.html
這個舊的備用數據庫怎么樣:
Command command = ((ICommandService)getSite().getService(ICommandService.class)).getCommand(commandId);
...
final Event trigger = new Event();
ExecutionEvent executionEvent = ((IHandlerService)getSite().getService(IHandlerService.class)).createExecutionEvent(command, trigger);
command.executeWithChecks(executionEvent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.