Get all TreeItems in an SWT Tree

僤鯓⒐⒋嵵緔 提交于 2019-12-24 09:37:47

问题


I want to get an array of all the TreeItems from my SWT Tree. However, the method included in the Tree class, getItems() only returns the items that are on the first level of the tree (i.e. that aren't children of anything).

Can someone suggest a way to get all of the children/items?


回答1:


The documentation of Tree#getItems() is very specific:

Returns a (possibly empty) array of items contained in the receiver that are direct item children of the receiver. These are the roots of the tree.

Here is some sample code that does the trick:

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);
    }
}


来源:https://stackoverflow.com/questions/17453515/get-all-treeitems-in-an-swt-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!