我创建了一个如下所示的数据库表,但行可以更多
id Name parent
1 color null
2 red 1
3 white 1
4 green 1
5 dark 4
6 light 4
public class TreeDemo extends javax.swing.JFrame {
/**
* Creates new form TreeDemo
*/
String Connection;
Connection conn;
Statement pst = null;
ResultSet rs = null;
DefaultTreeModel model;
LinkedHashMap<Integer, ObjClass> lhm = new LinkedHashMap<>();
public TreeDemo() {
initComponents();
model = (DefaultTreeModel) TreePro.getModel();
// retrieve Jtree From dataBase
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url = "jdbc:oracle:thin:@localhost:1521:XE";
conn = DriverManager.getConnection(url, "Hr", "Hr");
System.out.println("Connection Established");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM contacts order by node_id");
System.out.println("id name job" + rs);
// Retrieve rs from DataBase
while (rs.next()) {
int id = rs.getInt("node_Id");
String name = rs.getString("node_Name");
String par = rs.getString("node_Parent");
int lvl = rs.getInt("node_Level");
System.out.println(id + " " + name + " " + par + " " + lvl);
String parentId = rs.getString("node_Id");
String parentName = rs.getString("node_Name");
String paren = rs.getString("node_Parent");
int treeLvl = rs.getInt("node_Level");
Map<String, DefaultMutableTreeNode> parentsMap
= new HashMap<>();
DefaultTreeModel tbl = (DefaultTreeModel) TreePro.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tbl.getRoot();
DefaultMutableTreeNode Node1 = parentsMap.get("Root");
Node1 = new DefaultMutableTreeNode( paren );
parentsMap.put(parentId, Node1 );
root.add(Node1);
DefaultMutableTreeNode parent = parentsMap.get(parentName);
parent = new DefaultMutableTreeNode( parentName );
parentsMap.put(parentId, parent );
Node1.add(parent);
}
} catch (Exception e) {
System.out.println("connection error " + e);
}
}}}
&#13;
现在它创建了这样的jtree
Root
Null
-color
color
-red
color
-white
color
-green
green
-dark
green
-light
它应该像这样显示jtree:
Root
_color
-red
-white
_grenn
-dark
-light
注意:jtree可以是多级的。