KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > tree > NodeSorter


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.wcf.tree;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.HashSet JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.Set JavaDoc;
20
21 /**
22  * orders a set of nodes in pre- or postorder according to the tree model
23  *
24  * @author av
25  */

26 public class NodeSorter {
27
28   TreeModel model;
29   Set JavaDoc expanded = new HashSet JavaDoc();
30
31
32   private NodeSorter(TreeModel model) {
33     this.model = model;
34   }
35   
36
37   public static List JavaDoc preOrder(Set JavaDoc nodes, TreeModel model) {
38     NodeSorter ns = new NodeSorter(model);
39     return ns.order(nodes, true);
40   }
41
42
43   public static List JavaDoc postOrder(Set JavaDoc nodes, TreeModel model) {
44     NodeSorter ns = new NodeSorter(model);
45     return ns.order(nodes, false);
46   }
47   
48
49   List JavaDoc order(Set JavaDoc nodes, boolean preOrder) {
50     expandParents(nodes);
51     List JavaDoc list = new ArrayList JavaDoc();
52     Object JavaDoc[] roots = model.getRoots();
53     for (int i = 0; i < roots.length; i++)
54       order(roots[i], list, nodes, preOrder);
55     return list;
56   }
57   
58
59   void order(Object JavaDoc node, List JavaDoc list, Set JavaDoc nodes, boolean preOrder) {
60     if (preOrder && nodes.contains(node))
61       list.add(node);
62     if (expanded.contains(node)) {
63       Object JavaDoc[] children = model.getChildren(node);
64       for (int i = 0; i < children.length; i++)
65         order(children[i], list, nodes, preOrder);
66     }
67     if (!preOrder && nodes.contains(node))
68       list.add(node);
69   }
70
71
72   void expandParents(Set JavaDoc nodes) {
73     expanded.clear();
74     for (Iterator JavaDoc it = nodes.iterator(); it.hasNext();) {
75       Object JavaDoc node = it.next();
76       node = model.getParent(node);
77       while (node != null) {
78         expanded.add(node);
79         node = model.getParent(node);
80       }
81     }
82   }
83
84 }
85
Popular Tags