< Day Day Up > |
Recipe 10.5 Creating SWT Trees10.5.1 ProblemYou need to display data items in a hierarchical, collapsible-and-expandable form. 10.5.2 SolutionUse an SWT tree widget, based on the Tree and TreeItem classes. 10.5.3 DiscussionAs an example, we'll create a tree (TreeApp at this book's site) that contains several levels of items. Here is a selection of useful Tree methods:
The code in the TreeApp example creates a tree in this way: final Tree tree = new Tree(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); tree.setSize(290, 260); The items you add to a tree such as this are objects of the TreeItem class; here's a selection of TreeItem methods:
Adding items to a tree involves passing the parent of the item you're adding to the item's constructor. For example, to add 10 items to the tree widget, you can use code such as this: final Tree tree = new Tree(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); tree.setSize(290, 260); for (int loopIndex0 = 0; loopIndex0 < 10; loopIndex0++) { TreeItem treeItem0 = new TreeItem(tree, 0); treeItem0.setText("Level 0 Item " + loopIndex0); . . . } To add subitems to existing tree items, you can pass those existing tree items to the subitems' constructors, down to as many levels as you like. In this example, we'll give each top-level tree item 10 subitems and give each subitem 10 more subitems: final Tree tree = new Tree(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); tree.setSize(290, 260); for (int loopIndex0 = 0; loopIndex0 < 10; loopIndex0++) { TreeItem treeItem0 = new TreeItem(tree, 0); treeItem0.setText("Level 0 Item " + loopIndex0); for (int loopIndex1 = 0; loopIndex1 < 10; loopIndex1++) { TreeItem treeItem1 = new TreeItem(treeItem0, 0); treeItem1.setText("Level 1 Item " + loopIndex1); for (int loopIndex2 = 0; loopIndex2 < 10; loopIndex2++) { TreeItem treeItem2 = new TreeItem(treeItem1, 0); treeItem2.setText("Level 2 Item " + loopIndex2); } } } That creates the tree shown in Figure 10-4. Figure 10-4. An SWT treeFor more on trees, such as handling selection events, see the following recipes.
10.5.4 See AlsoRecipe 10.6 on handling tree events; Recipe 10.7 on adding checkboxes to tree items; Recipe 10.8 on adding images to tree items; Chapter 8 in Eclipse (O'Reilly). |
< Day Day Up > |