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

java: Make multi level dynamic jtree from database table

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

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);
        }
 
    }}}

现在它像这样创建 jtree

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

它应该像这样显示 jtree:

 Root
  _color
    -red
    -white
    _grenn
      -dark
      -light

注意:jtree 可以是多级的。

这是我给你的建议。因为我没有你的数据库,所以我使用了一个二维数组作为数据源。我希望按照我的示例中所示编写代码对您来说没有问题

import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TreeExample implements Runnable {

    private static final Object NODES[][] =
            {{1, "color", null}, {2, "red", 1}, {3, "white", 1}, {4, "green", 1}, {5, "dark", 4}, {6, "light", 4}};

    @Override
    public void run() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        // use while loop to make you easer to switch to your result set.
        int index = 0;
        Map<Integer, DefaultMutableTreeNode> nodesMap = new HashMap<>();
        while (index < NODES.length) {
            Integer id = getValue(NODES[index], 0, Integer.class);
            Integer parentId = getValue(NODES[index], 2, Integer.class);
            String name = getValue(NODES[index], 1, String.class);
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
            nodesMap.put(id, node);
            if (parentId == null) {
                root.add(node);
            } else {
                nodesMap.get(parentId).add(node);
            }
            index++;
        }
        JTree tree = new JTree(new DefaultTreeModel(root));
        expandTree(tree);
        JFrame frm = new JFrame("Tree test");
        frm.add(new JScrollPane(tree));
        frm.setSize(300, 200);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    private <T> T getValue(Object[] array, int index, Class<T> clazz) {
        return clazz.cast(array[index]);
    }

    private void expandTree(JTree tree) {
        int row = 0;
        while (tree.getRowCount() > row) {
            tree.expandRow(row++);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TreeExample());
    }
}