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

时间:2022-06-18 12:36:04

i have make a database table like the following, but the rows can be more

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

id  Name     parent   
1  color      null        
2  red        1        
3  white      1         
4  green      1         
5  dark       4        
6  light      4 
  • To retrieve the table from database i already written the code following. i search all over the internet but unable to find the solution that's what i found, i am successful to make a connection with Db, and print the resultSet values using while loop , but unable to make jtree, i mean i make jtree but its not working as it should do.
  • 要从数据库中检索表,我已经编写了以下代码。我在互联网上搜索但无法找到我发现的解决方案,我成功与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);
        }
 
    }}}

Now it's creates jtree like this

现在它创建了这样的jtree

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

It should show jtree like this:

它应该像这样显示jtree:

 Root
  _color
    -red
    -white
    _grenn
      -dark
      -light

Note: the jtree can be multilevel.

注意:jtree可以是多级的。

1 个解决方案

#1


1  

Here is my suggestion for you. Because I haven't your database, I've used a two-dimensional array as data source. I hope it makes no problem for you to make your code as it shown in my example

这是我对你的建议。因为我没有你的数据库,所以我使用了二维数组作为数据源。我希望你的代码如我的例子中所示,没有问题

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

#1


1  

Here is my suggestion for you. Because I haven't your database, I've used a two-dimensional array as data source. I hope it makes no problem for you to make your code as it shown in my example

这是我对你的建议。因为我没有你的数据库,所以我使用了二维数组作为数据源。我希望你的代码如我的例子中所示,没有问题

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