Yesterday, I tried to bind the jTree to the database. Today, I encountered another problem: If my database records change, I need to refresh all nodes in the jTree immediately. What should I do? After trying, this small problem is also solved.
The basic idea of binding a previously written jTree to a database is to create a DefaultMutableTreeNode as the root node, and then add new nodes on its basis. Therefore, to refresh the jTree, You can first clear all the subnodes under the root node and then re-bind it. The specific process is as follows:
1. How to clear the tree:
/** Clear tree */private void jmenuitem9actionreceivmed (java. awt. event. actionEvent evt) {conn myconn = new conn (); myconn. updateDB ("delete from tempDocFiles"); // delete the database record JOptionPane. showMessageDialog (this, "the file list is cleared successfully! \ N \ r you can continue to upload files. "); Top. removeAllChildren (); // clear all child nodes of the root node jTree1.updateUI (); // refresh tree}
2. Modify the method of binding the tree:
/** Fill in JTree */public void showTree () {conn myconn = new conn (); ResultSet nodeRs; ResultSet leafr; if (top. isLeaf () = false) // check whether the root node is a leaf node before binding. If yes, the tree is empty. If not, this indicates that the tree has already been bound with content, and its subnodes are cleared from top. removeAllChildren (); try {nodeRs = myconn. queryDB ("select distinct cType from tempDocFiles where position = '" + this. position + "'"); leafr = myconn. queryDB ("select cType, fileName from tempDocFiles where position =' "+ This. position +" '"); if (! NodeRs. next () {JOptionPane. showMessageDialog (this, "No File Upload record currently. please upload the file first! ");} Else {nodeRs. beforeFirst (); while (nodeRs. next () {DefaultMutableTreeNode node = new DefaultMutableTreeNode (nodeRs. getObject (1); top. add (node); while (leafr. next () {if (leafr. getObject (1 ). toString (). equals (nodeRs. getObject (1) {DefaultMutableTreeNode leafnode = new DefaultMutableTreeNode (leafr. getObject (2); node. add (leafnode) ;}} top. add (node); leafr. beforeFirst ();} jTree1.updateUI () ;}} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}
3. Add a program that calls the preceding method elsewhere. In this program, the tree structure can be refreshed in real time.