java:从数据库表中创建多级动态jtree

时间:2018-05-09 10:41:52

标签: java swing jtree

我创建了一个如下所示的数据库表,但行可以更多

id  Name     parent   
1  color      null        
2  red        1        
3  white      1         
4  green      1         
5  dark       4        
6  light      4 
  • 要从数据库中检索表,我已经编写了以下代码。我在互联网上搜索但无法找到我找到的解决方案,我成功与Db建立连接,并使用while循环打印resultSet值,但无法生成jtree,我的意思是我制作jtree但它不能正常工作。



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;
&#13;
&#13;

现在它创建了这样的jtree

Root
 Null
  -color
 color
  -red
 color
  -white
 color
  -green
 green
  -dark
 green
  -light

它应该像这样显示jtree:

 Root
  _color
    -red
    -white
    _grenn
      -dark
      -light

注意:jtree可以是多级的。

0 个答案:

没有答案