gpt4 book ai didi

java - 获取 SWT 树中的所有 TreeItems

转载 作者:行者123 更新时间:2023-11-29 07:56:20 25 4
gpt4 key购买 nike

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

有人可以建议一种获取所有子项/项目的方法吗?

最佳答案

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.

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

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

关于java - 获取 SWT 树中的所有 TreeItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com