如何使用IStructuredSelection获得多个选定的项目?

时间:2014-10-25 06:13:59

标签: java eclipse-plugin

我尝试开发新闻eclipse工具(eclipse插件),所以我想从工作区中获取多个选定的项目。我尝试了getFirstElement(),但它只获得了第一个选定的项目。

非常感谢

以下是一些代码:

public Object execute(ExecutionEvent event) throws ExecutionException {
    part = HandlerUtil.getActivePart(event);
    window = HandlerUtil.getActiveWorkbenchWindowChecked(event);

        selection = HandlerUtil.getActiveMenuSelection(event);

    if (selection instanceof IStructuredSelection) {
        IStructuredSelection structured = (IStructuredSelection)selection;

        IJavaProject project = null;

        Object elem = structured.getFirstElement();

        if (elem instanceof IJavaProject) {
            project = (IJavaProject)elem;
        } else if (elem instanceof IProject) {
            project = (IJavaProject)JavaCore.create((IProject)elem);
        }

        if (project != null) {
                        }
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

顾名思义IStructuredSelection.getFirstElement()只给你第一个选择。

要获取所有选择,请使用iterator()toArray()toList()方法中的任何一种。

例如:

IStructuredSelection structured = (IStructuredSelection)selection;

for (Object elem : structured.toList()) {
    IJavaProject project = null;

    if (elem instanceof IJavaProject) {
        project = (IJavaProject)elem;
    } else if (elem instanceof IProject) {
        project = (IJavaProject)JavaCore.create((IProject)elem);
    }

    if (project != null) {
       ... your code
    }        
}