要创建树,首先要创建树控件,然后添加 TreeItems 中包装的字符串数据。TreeItems 可以包含其他 TreeItems,这样就可以创建值的层次结构。清单 8 创建了图 7 中所示的树。
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->1 // Create the Tree
2 protected Tree createTree(Composite parent, int mode, Node root) {
3 tree = new Tree(parent, mode | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
4 tree.addSelectionListener(new SelectionListener() {
5 :
6 });
7 setTreeContents(root);
8 return tree;
9 }
10 protected void setTreeContents(Node root) {
11 tree.removeAll();
12 TreeItem ti = new TreeItem(tree, SWT.NONE);
13 setTreeItemContents(ti, root);
14 }
15 protected void setTreeItemContents(TreeItem ti, Node root) {
16 ti.setText(root.getName());
17 java.util.List children = root.getChildren();
18 if (children != null && children.size() > 0) {
19 for (Iterator i = children.iterator(); i.hasNext();) {
20 Node n = (Node)i.next();
21 TreeItem tix = new TreeItem(ti, SWT.NONE);
22 setTreeItemContents(tix, n);
23 }
24 }
25 }
26 :
27 // sample creation code
28 protected void addChildren(Node n, int count, int depth, String prefix) {
29 if (depth > 0) {
30 for (int i = 0; i < count; i++) {
31 String name = prefix + '.' + i;
32 Node child = new Node(name);
33 n.addChild(child);
34 addChildren(child, count, depth - 1, name);
35 }
36 }
37 }
38 Node root = new Node("<root>");
39 addChildren(root, 3, 3, "Child");
40 tree = createTree(this, SWT.CHECK, root);
41
图 7. 树的例子
复选框是可选的。