如何从 Eclipse 插件获取包资源管理器中的选定节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/585802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 13:33:46  来源:igfitidea点击:

How to get the selected node in the package explorer from an Eclipse plugin

javaeclipseuser-interfaceeclipse-rcprcp

提问by Benjamin

I'm writing an Eclipse command plugin and want to retrieve the currently selected node in the package explorer view. I want to be able to get the absolute filepath, where the selected node resides on the filesystem (i.e. c:\eclipse\test.html), from the returned result.

我正在编写一个 Eclipse 命令插件,并希望在包资源管理器视图中检索当前选定的节点。我希望能够从返回的结果中获取绝对文件路径,其中所选节点驻留在文件系统(即 c:\eclipse\test.html)上。

How do I do this ?

我该怎么做呢 ?

回答by Fabian Steeg

The first step is to get a selection service, e.g. from any view or editor like this:

第一步是获取选择服务,例如从任何视图或编辑器中获取,如下所示:

ISelectionService service = getSite().getWorkbenchWindow()
            .getSelectionService();

Or, as VonC wrote, you could get it via the PlatformUI, if you are neither in a view or an editor.

或者,如 VonC 所写,如果您既不在视图中也不在编辑器中,则可以通过 PlatformUI 获取它。

Then, get the selection for the Package Explorer and cast it to an IStructuredSelection:

然后,获取 Package Explorer 的选择并将其转换为 IStructuredSelection:

IStructuredSelection structured = (IStructuredSelection) service
            .getSelection("org.eclipse.jdt.ui.PackageExplorer");

From that, you can get your selected IFile:

从中,您可以获得您选择的 IFile:

IFile file = (IFile) structured.getFirstElement();

Now to get the full path, you will have to get the location for the IFile:

现在要获取完整路径,您必须获取 IFile 的位置:

IPath path = file.getLocation();

Which you then can finally use to get the real full path to your file (among other things):

然后您最终可以使用它来获取文件的真实完整路径(除其他外):

System.out.println(path.toPortableString());

You can find more information on the selection service here: Using the Selection Service.

您可以在此处找到有关选择服务的更多信息:使用选择服务

回答by VonC

The code would be like:

代码如下:

IWorkbenchWindow window =
    PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelection selection = window.getSelectionService().getSelection("org.eclipse.jdt.ui.PackageExplorer");

You view an example in an Action like this LuaFileWizardAction class.

您可以在类似LuaFileWizardAction 类的 Action 中查看示例。