0

我正在做一个测试项目并遵循Vogella 的 RCP 教程。之后,我对其进行了一些更改,例如。创建了一个JFace TreeView. 现在我希望如果用户双击一个TreeView元素,它会打开另一个Part. 我有它的命令,但我不知道如何调用它。如果您查看教程,您可能会注意到它仅使用部件,而不是视图,而且我没有Application.java启动工作台的类。因此,以下方法对我不起作用:

  1. IHandlerService handlerService = (IHandlerService) viewer.getSite().getService(IHandlerService.class);
  2. IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IHandlerService handlerService = (IHandlerService)window.getService(IHandlerService.class); handlerService.executeCommand(cmdID, null);

他们两个都给我NullPointerException

4

2 回答 2

1

根据 Lars Vogel 的说法,推荐的方法是注入如下所示的服务(这对我有用)。唯一的障碍是根据插件规则,包 org.eclipse.e4.core.commands 似乎无法访问(可能尚未导出)。

但这有效:

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

https://groups.google.com/forum/#!topic/vogella/n5ztV-8GmkU

于 2013-07-01T13:10:49.033 回答
0

这个旧待机怎么样:

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);
于 2012-10-04T13:53:33.303 回答