获取 SWT 树中的所有树项 [英] Get all TreeItems in an SWT Tree

查看:39
本文介绍了获取 SWT 树中的所有树项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的 SWT 树中获取所有 TreeItem 的数组.但是,包含在 Tree 类中的方法 getItems() 仅返回位于树的第一级(即,不是任何子项)的项.

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?

推荐答案

Tree#getItems() 非常具体:

返回一个(可能是空的)包含在接收者中的项目数组是接收者的直接项目子项.这些是树的根.

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

这篇关于获取 SWT 树中的所有树项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆