限制 ElementTreeSelectionDialog

restrict the ElementTreeSelectionDialog

我想实现 Workspace Browse。我写了下面的代码。

ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
            Display.getDefault().getActiveShell(),
            new WorkbenchLabelProvider(),
            new BaseWorkbenchContentProvider());

dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.open();

如何将代码更改为仅显示包含“.ecore”文件的根元素(项目或文件夹)?当用户折叠任何根元素时,仅显示 .ecore 个文件?

您可以向对话框添加查看器过滤器以限制显示的内容。

dialog.addFilter(new FileExtensionFilter("ecore"));

添加过滤器。

文件扩展名过滤器类似于:

public class FileExtensionFilter extends ViewerFilter {

  private String fTargetExtension;

  public FileExtensionFilter(String targetExtension) {
    fTargetExtension = targetExtension;
  }

  @Override
  public boolean select(Viewer viewer, Object parent, Object element) {
    if (element instanceof IFile) {
      return ((IFile)element).getName().toLowerCase().endsWith("." + fTargetExtension); 
    }

    if (element instanceof IProject && !((IProject)element).isOpen())
      return false;

    if (element instanceof IContainer) { // i.e. IProject, IFolder
      try {
        IResource[] resources = ((IContainer)element).members();
        for (IResource resource : resources) {
          if (select(viewer, parent, resource))
            return true;
        }
      } catch (CoreException e) {
        // Ignore
      }
    }

    return false;  
  }
}

这是基于org.eclipse.pde.internal.ui.util.FileExtensionFilter

对于 Java 16 及更高版本,select 方法可以使用“instanceof type patterns”进行简化:

@Override
public boolean select(Viewer viewer, Object parent, Object element) {
  if (element instanceof IFile file) {
    return file.getName().toLowerCase().endsWith("." + fTargetExtension);
  }

  if (element instanceof IProject project && !project.isOpen())
    return false;

  if (element instanceof IContainer container) { // i.e. IProject, IFolder
    try {
      IResource[] resources = container.members();
      for (IResource resource : resources) {
        if (select(viewer, parent, resource))
          return true;
      }
    } catch (final CoreException e) {
      // Ignore
    }
  }

  return false;
}