The ExecutionEvent in the execute method which is triggered when the new item is selected on the menu does not seem to refer to the file that was right clicked on. I wonder if I need to add listener for this and if so will this interfere with the execution method.
What you get in the event is the current selection which may be a file or may be something else depending on how you defined the menu 'enabledWhen'. You can get the file from the selection.
IStructuredSelection selection = HandlerUtil.getCurrentStructuredSelection(event);
if (!selection.isEmpty()) {
IFile file = Adapters.adapt(selection.getFirstElement(), IFile.class, true);
if (file != null) {
... your code
}
}
In some cases an adapter to IFile
is not available but one to IResource
is. In this case use:
IResource resource = Adapters.adapt(selection.getFirstElement(), IResource.class);
if (resource instanceof IFile) {
IFile file = (IFile)resource;
}
Note: getCurrentStructuredSelection
and Adapters
are relatively new APIs. In older versions of Eclipse you will need slightly more complicated code.
HandlerUtil
is org.eclipse.ui.handlers.HandlerUtil
in the org.eclipse.ui.workbench
plug-in, Adapters
is org.eclipse.core.runtime.Adapters
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.