01: /*
02: * MyGWT Widget Library
03: * Copyright(c) 2007, MyGWT.
04: * licensing@mygwt.net
05: *
06: * http://mygwt.net/license
07: */
08: package net.mygwt.ui.client.util;
09:
10: import net.mygwt.ui.client.data.Model;
11: import net.mygwt.ui.client.widget.tree.Tree;
12: import net.mygwt.ui.client.widget.tree.TreeItem;
13:
14: import com.google.gwt.user.client.DOM;
15: import com.google.gwt.user.client.Element;
16:
17: /**
18: * Various ways of populating trees.
19: *
20: * @see Tree
21: */
22: public class TreeBuilder {
23:
24: /**
25: * Populates a tree from existing dom elements. The tree item text is taken
26: * from the 'title' attribute of the element.
27: *
28: * @param tree the tree
29: * @param root the root element
30: */
31: public static void buildTree(Tree tree, Element root) {
32: process(tree.getRootItem(), root);
33: }
34:
35: /**
36: * Populates a tree from the given model.
37: *
38: * @param tree the tree
39: * @param model the model
40: */
41: public static void buildTree(Tree tree, Model model) {
42: TreeItem root = tree.getRootItem();
43: for (int i = 0; i < model.getChildCount(); i++) {
44: Model m = model.getChild(i);
45: TreeItem item = new TreeItem();
46: item.setText(m.toString());
47: root.add(item);
48: process(item, m);
49: }
50: }
51:
52: private static void process(TreeItem parentItem, Model model) {
53: for (int i = 0; i < model.getChildCount(); i++) {
54: Model m = model.getChild(i);
55: TreeItem item = new TreeItem();
56: item.setText(m.toString());
57: parentItem.add(item);
58: process(item, m);
59: }
60: }
61:
62: private static void process(TreeItem item, Element parent) {
63: int size = DOM.getChildCount(parent);
64: for (int i = 0; i < size; i++) {
65: Element li = DOM.getChild(parent, i);
66: TreeItem childItem = new TreeItem();
67: String id = DOM.getElementAttribute(li, "id");
68: if (id != null && !id.equals("")) {
69: childItem.setId(id);
70: }
71: childItem.setText(DOM.getElementProperty(li, "title"));
72: item.add(childItem);
73: for (int j = 0; j < DOM.getChildCount(li); j++) {
74: Element subList = DOM.getChild(li, j);
75: process(childItem, subList);
76: }
77: }
78: }
79:
80: }
|