获取树中所有选中的项目

get all checked items in a tree

我想在点击新建按钮时获取选中项的名称。不幸的是,我无法通过为项目添加侦听器来解决此问题。此代码有解决方案吗?

此示例代码:

public class SWTTreeExample {
    private Shell shell;
    public static Tree check;
    public void run() {
    Display display = new Display();
    shell = new Shell(display);
    shell.setText("TreeExample");
    createContents(shell);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  private void createContents(Composite composite) {
    composite.setLayout(new GridLayout(1, true));
    GridData data = new GridData(GridData.FILL_BOTH);
    Button btnNewButton = new Button(shell, SWT.NONE);
    btnNewButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            TreeItem[] items = check.getSelection();
            System.out.println(items[0]);
        }
    });
    btnNewButton.setText("New Button");
    check = new Tree(composite, SWT.CHECK | SWT.BORDER);
    data = new GridData(GridData.FILL_BOTH);
    check.setLayoutData(data);
    fillTree(check);
  }
  private void fillTree(Tree tree) {
    tree.setRedraw(false);
    for (int i = 0; i < 1; i++) {
      TreeItem item = new TreeItem(tree, SWT.NONE);
      item.setText("Root Item " + i);
      for (int j = 0; j < 3; j++) {
        TreeItem child = new TreeItem(item, SWT.NONE);
        child.setText("Child Item " + i + " - " + j);
      }
    }
    tree.setRedraw(true);
  }
  public static void main(String[] args) {
    new SWTTreeExample().run();
  }
}

对于 Tree,您需要在树中递归查找选中的项目。类似于:

  private List<String> getChecked(final Tree tree)
  {
    final List<String> checked = new ArrayList<>();

    final TreeItem [] topItems = tree.getItems();

    for (final TreeItem item : topItems) {
      if (item.getChecked()) {
        checked.add(item.getText());
      }

      addChecked(checked, item);
    }

    return checked;
  }

  private void addChecked(final List<String> checked, final TreeItem treeItem)
  {
    final TreeItem[] items = treeItem.getItems();

    for (final TreeItem item : items) {
      if (item.getChecked()) {
        checked.add(item.getText());
      }

      addChecked(checked, item);
    }
  }

注意:JFace CheckboxTreeViewer 更容易用于此类事情,并且有一个 getCheckedElements() 方法。