我想从SWT树中获取所有TreeItem的数组。但是,Tree类中包含的方法getItems()
仅返回树的第一级上的项(即不是任何子项的子项)。
有人可以建议一种方法来获取所有儿童/物品吗?
答案 0 :(得分:5)
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);
}
}