1

我想从我的 SWT 树中获取所有 TreeItems 的数组。但是,Tree 类中包含的方法getItems()只返回树的第一级上的项目(即不是任何事物的孩子)。

有人可以建议一种获取所有孩子/物品的方法吗?

4

1 回答 1

6

的文档Tree#getItems()非常具体:

返回接收器中包含的项目(可能为空)数组,这些项目是接收器的直接项目子项。这些是树的根。

这是一些可以解决问题的示例代码:

public static void main(String[] args)
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new FillLayout());

    final Tree tree = new Tree(shell, SWT.MULTI);

    TreeItem parentOne = new TreeItem(tree, SWT.NONE);
    parentOne.setText("Parent 1");
    TreeItem parentTwo = new TreeItem(tree, SWT.NONE);
    parentTwo.setText("Parent 2");

    for (int i = 0; i < 10; i++)
    {
        TreeItem item = new TreeItem(parentOne, SWT.NONE);
        item.setText(parentOne.getText() + " child " + i);

        item = new TreeItem(parentTwo, SWT.NONE);
        item.setText(parentTwo.getText() + " child " + i);
    }

    parentOne.setExpanded(true);
    parentTwo.setExpanded(true);

    List<TreeItem> allItems = new ArrayList<TreeItem>();

    getAllItems(tree, allItems);

    System.out.println(allItems);

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

private static void getAllItems(Tree tree, List<TreeItem> allItems)
{
    for(TreeItem item : tree.getItems())
    {
        getAllItems(item, allItems);
    }
}

private static void getAllItems(TreeItem currentItem, List<TreeItem> allItems)
{
    TreeItem[] children = currentItem.getItems();

    for(int i = 0; i < children.length; i++)
    {
        allItems.add(children[i]);

        getAllItems(children[i], allItems);
    }
}
于 2013-07-03T17:45:53.603 回答