|
The algorithm is simple; it iterates through the top-level items of the tree and compares their text contents with the search string (lines 43 to 52 in listing 6). When the search string is found in one of the tree items, that tree item is selected (line 48). If that string is not found, the Search Error message, Could not find: 'TreeItemX', displays (lines 21 to 27).
Now, the only modification to be done is to add the SearchListener to the tree’s collection of key listeners, as shown in line 23 of listing 7.
Listing 7. Basic tree search
1:import java.util.Random;
2:
3:import org.eclipse.swt.SWT;
4:import org.eclipse.swt.layout.FillLayout;
5:import org.eclipse.swt.widgets.Display;
6:import org.eclipse.swt.widgets.Shell;
7:import org.eclipse.swt.widgets.Tree;
8:import org.eclipse.swt.widgets.TreeColumn;
9:import org.eclipse.swt.widgets.TreeItem;
10:
11 ublic class Searching {
12: public static void main(String[] args) {
13: Display display = new Display();
14:
15: Shell shell = new Shell(display);
16: shell.setText("Searching" ;
17: shell.setLayout(new FillLayout());
18: shell.setSize(400, 300);
19:
20: Tree tree = new Tree(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL
21: | SWT.FULL_SELECTION);
22: tree.setHeaderVisible(true);
23: tree.addKeyListener(new SearchListener());
24:
25: TreeColumn column1 = new TreeColumn(tree, SWT.NONE);
26: column1.setText("TreeColumn0" ;
27: column1.setWidth(200);
28: column1.setAlignment(SWT.LEFT);
29: column1.addSelectionListener(new SortTreeListener());
30:
31: TreeColumn column2 = new TreeColumn(tree, SWT.NONE);
32: column2.setText("TreeColumn1" ;
33: column2.setWidth(200);
34: column2.setAlignment(SWT.CENTER);
35: column2.addSelectionListener(new SortTreeListener());
36:
37: Random generator = new Random();
38:
39: for (int i = 0; i < 5; i++) {
40: TreeItem treeItem = new TreeItem(tree, 0);
41: treeItem.setText(new String[] { "TreeItem" + i,
42: Integer.toString(generator.nextInt()) });
43: for (int j = 0; j < 5; j++) {
44: TreeItem subTreeItem = new TreeItem(treeItem, SWT.NONE);
45: subTreeItem.setText(new String[] { "SubTreeItem" + j,
46: Integer.toString(generator.nextInt()) });
47: for (int k = 0; k < 5; k++) {
48: TreeItem subSubTreeItem = new TreeItem(subTreeItem,
49: SWT.NONE);
50: subSubTreeItem.setText(new String[] { "SubSubTreeItem" + k,
51: Integer.toString(generator.nextInt()) });
52: }
53: }
54: }
55:
56: shell.open();
57: while (!shell.isDisposed()) {
58: if (!display.readAndDispatch())
59: display.sleep();
60: }
61: display.dispose();
62: }
63:}
Finally, the search algorithm can be easily modified to do a recursive search of all the tree’s items. |
|