1 10 package mondrian.gui; 11 12 import javax.swing.event.TreeModelListener ; 13 import javax.swing.tree.TreePath ; 14 import java.sql.Connection ; 15 import java.sql.DatabaseMetaData ; 16 import java.sql.ResultSet ; 17 import java.util.ArrayList ; 18 import java.util.List ; 19 import java.util.Vector ; 20 21 26 public class JDBCTreeModel implements javax.swing.tree.TreeModel { 27 private Vector treeModelListeners = new Vector (); 28 Connection connection; 29 DatabaseMetaData metadata; 30 List catalogs; 31 Node root; 32 33 34 public JDBCTreeModel(Connection c) { 35 connection = c; 36 try { 37 metadata = connection.getMetaData(); 38 catalogs = new ArrayList (); 39 String catalogName = connection.getCatalog(); 40 Node cat = new Node(catalogName, Node.CATALOG); 41 42 ResultSet trs = metadata.getTables(cat.name, null, null, null); 43 while (trs.next()) { 44 Node table = new Node(trs.getString(3), Node.TABLE); 45 cat.children.add(table); 46 ResultSet crs = metadata.getColumns(cat.name, null, table.name, null); 48 while (crs.next()) { 49 Node column = new Node(crs.getString(4), Node.COLUMN); 50 table.children.add(column); 51 } 52 } 53 root = cat; 54 55 } catch (Exception ex) { 56 ex.printStackTrace(); 57 } 58 } 59 60 61 68 public void addTreeModelListener(TreeModelListener l) { 69 treeModelListeners.add(l); 70 } 71 72 84 public Object getChild(Object parent, int index) { 85 if (parent instanceof Node) { 86 return ((Node)parent).children.get(index); 87 } 88 89 return null; 90 } 91 92 101 public int getChildCount(Object parent) { 102 if (parent instanceof Node) { 103 return ((Node)parent).children.size(); 104 } 105 return 0; 106 } 107 108 118 public int getIndexOfChild(Object parent, Object child) { 119 if (parent instanceof Node) { 120 return ((Node)parent).children.indexOf(child); 121 } 122 123 return -1; 124 } 125 126 132 public Object getRoot() { 133 return root; 134 } 135 136 147 public boolean isLeaf(Object node) { 148 return getChildCount(node) == 0; 149 } 150 151 158 public void removeTreeModelListener(TreeModelListener l) { 159 treeModelListeners.remove(l); 160 } 161 162 171 public void valueForPathChanged(TreePath path, Object newValue) { 172 } 173 174 class Node { 175 static final int CATALOG = 0; 176 static final int TABLE = 1; 177 static final int COLUMN = 2; 178 String name; 179 int type; 180 ArrayList children; 181 182 public Node(String n, int t) { 183 name = n; 184 type = t; 185 children = new ArrayList (); 186 } 187 188 public String toString() { 189 return name; 190 } 191 } 192 } 193 194 | Popular Tags |