简体   繁体   中英

Jtree from folder path saved in database

i want to create a jtree from folder path saved in database like TestFolder/ABCD/CDEF/ghml TestFolder/ABCD/THYU/UVWZ iam saving only the path not parent structure so when i try to create tree structure it works fine for single path(TestFolder/ABCD/CDEF/ghml) i want buid a complete tree struture if any one have idea please help

public class MainClass {

public static void main(String[] a) throws ClassNotFoundException, SQLException {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new JTreeEvents());
    f.setSize(500, 500);
    f.setVisible(true);
}
}

enter code here

 class JTreeEvents extends JPanel {

private String driver = new String("com.mysql.jdbc.Driver");
private String url = new String("jdbc:mysql:);
private String user = new String("root");
private String password = new String("128");
private Connection dbCon;
List<String> arrayList;
Map<String, Map<Integer, String>> map;
String[] folderArr;
PreparedStatement ps = null;
java.sql.Statement s;
ResultSet r;
DefaultMutableTreeNode top;
DefaultTreeModel dt;
DefaultMutableTreeNode trees;
DefaultTreeModel model;
DefaultMutableTreeNode child, subchild;
//tree  

JTree jtree;

JTextField jtf;

public JTreeEvents() throws ClassNotFoundException, SQLException {
    //------------------------------------------------------------------
    Class.forName(driver);
    dbCon = DriverManager.getConnection(url, user, password);
    s = dbCon.createStatement();
    r = s.executeQuery("SELECT * FROM project p where p.name='MyFolder4'");
    arrayList = new ArrayList<String>();
    map = new HashMap<String, Map<Integer, String>>();
    Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
    DefaultMutableTreeNode root;
    MutableTreeNode parent;
    DefaultMutableTreeNode parentnode;
    TreePath path = null;
    while (r.next()) {
        arrayList.add(r.getString("path"));
    }

    for (String str : arrayList) {
        if (str != null) {
            folderArr = str.split("/");
            String projName = str.split("/")[0];
            root = new DefaultMutableTreeNode(projName);
            model = new DefaultTreeModel(root);
            jtree = new JTree(model);

            for (int i = 0; i < folderArr.length; i++) {

                if (i == 0) {
                    parent = new DefaultMutableTreeNode(folderArr[0]);
                } else {
                    path = jtree.getNextMatch(folderArr[i - 1].toString(), 0, Position.Bias.Forward);
                    if (path != null) {
                        System.out.println(path);
                    }
                    parent = (DefaultMutableTreeNode) (MutableTreeNode)                                                            path.getLastPathComponent();                                       

                }  
enter code here
                model = (DefaultTreeModel) jtree.getModel();
                model.insertNodeInto((DefaultMutableTreeNode) new                           DefaultMutableTreeNode(folderArr[i]), parent, parent.getChildCount());

                model.reload();
                jtree.expandPath(path);
            }
        }

    }

    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(jtree, v, h);

    add(jsp, BorderLayout.CENTER);

    jtf = new JTextField("", 20);
    add(jtf, BorderLayout.SOUTH);

    jtree.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            doMouseClicked(me);
        }
    });
}
enter code here
void doMouseClicked(MouseEvent me) {
    TreePath tp = jtree.getPathForLocation(me.getX(), me.getY());
    if (tp != null) {
        jtf.setText(tp.toString());
    } else {
        jtf.setText("");
    }
}
      private TreePath find(DefaultMutableTreeNode root, String s) {
@SuppressWarnings("unchecked")
Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration();
while (e.hasMoreElements()) {
    DefaultMutableTreeNode node = e.nextElement();
    if (node.toString().equalsIgnoreCase(s)) {
        return new TreePath(node.getPath());
          }
 }
 return null;
    }
 }

There's a couple of things that do not work in your code. First the code to build the tree can be much simplified like this:

public JTreeEvents() throws ClassNotFoundException, SQLException {
  // ... fill the array list from the database ..

  for (String path: arrayList) {
    DefaultMutableTreeNode currentParent = root;
    String[] pathComponents = path.split("/");
    for (String comp: pathComponents) {
      DefaultMutableTreeNode child = findChild(currentParent, comp);
      if (child == null) {
        child = new DefaultMutableTreeNode(comp);
        currentParent.add(child);
      }
      currentParent = child;
    }
  }

  model = new DefaultTreeModel(root);
  jtree = new JTree(model);

  // ... build the rest of the GUI components
}

private DefaultMutableTreeNode findChild(DefaultMutableTreeNode parent, String s) {
  for (int i=0; i<parent.getChildCount(); i++) {
    DefaultMutableTreeNode child = (DefaultMutableTreeNode) parent.getChildAt(i);
    if (s.equals(child.getUserObject())) return child;
  }
  return null;
}

The second thing is that JPanel comes by default with no layout, so you need to add one explicitely, before adding any component to it:

this.setLayout(new BorderLayout());

So the full code of JTreeEvent becomes, after getting rid of all the unused variable declarations:

public class JTreeEvents extends JPanel {
  private String driver = new String("com.mysql.jdbc.Driver");
  private String url = new String("jdbc:mysql:");
  private String user = new String("root");
  private String password = new String("128");
  private Connection dbCon;
  List<String> arrayList;
  PreparedStatement ps = null;
  java.sql.Statement s;
  ResultSet r;
  DefaultMutableTreeNode root = new DefaultMutableTreeNode("/");
  DefaultTreeModel model;
  JTree jtree;
  JTextField jtf;

  public JTreeEvents() throws ClassNotFoundException, SQLException {
    Class.forName(driver);
    dbCon = DriverManager.getConnection(url, user, password);
    s = dbCon.createStatement();
    r = s.executeQuery("SELECT * FROM project p where p.name='MyFolder4'");
    arrayList = new ArrayList<String>();
    while (r.next()) {
      arrayList.add(r.getString("path"));
    }

    for (String path: arrayList) {
      DefaultMutableTreeNode currentParent = root;
      String[] pathComponents = path.split("/");
      for (String comp: pathComponents) {
        DefaultMutableTreeNode child = findChild(currentParent, comp);
        if (child == null) {
          child = new DefaultMutableTreeNode(comp);
          currentParent.add(child);
        }
        currentParent = child;
      }
    }

    setLayout(new BorderLayout());

    model = new DefaultTreeModel(root);
    jtree = new JTree(model);

    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(jtree, v, h);
    add(jsp, BorderLayout.CENTER);

    jtf = new JTextField("", 20);
    add(jtf, BorderLayout.SOUTH);

    jtree.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent me) {
        doMouseClicked(me);
      }
    });
  }

  void doMouseClicked(MouseEvent me) {
    TreePath tp = jtree.getPathForLocation(me.getX(), me.getY());
    if (tp != null) {
      jtf.setText(tp.toString());
    } else {
      jtf.setText("");
    }
  }

  private DefaultMutableTreeNode findChild(DefaultMutableTreeNode parent, String s) {
    for (int i=0; i<parent.getChildCount(); i++) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode) parent.getChildAt(i);
      if (s.equals(child.getUserObject())) return child;
    }
    return null;
  }
}

I tested it without the database stuff, by manually adding paths to the array list in my code, and it works nicely:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM