Search code examples
javaswingjtreetreenode

getting the parent from the given child node


 public class TabularMibTreeModel extends DefaultTreeModel {
     public TabularMibTreeModel() {
         super(new DefaultMutableTreeNode("Tablular MIBs"));
         loadParentMibs();
     }

     @Override
     public void reload() {
         super.reload();
     }

     private void loadParentMibs() {
           try {
                 ResultSet rs=Application.getDBHandler().executeQuery(SQLQueries.SELECT_TABULARMIBS_PARENT);

               while(rs.next()){            
                    String entryOID = rs.getString("mt_oid");       
                    DefaultMutableTreeNode node=new DefaultMutableTreeNode(new MibNode(entryOID, "Parent"));
                    node.add(new DefaultMutableTreeNode(Boolean.TRUE));

                    ((DefaultMutableTreeNode) getRoot()).insert(node,((DefaultMutableTreeNode)getRoot()).getChildCount())

                     node=null;

                 }

          } catch (SQLException e) {
           e.printStackTrace();
         }
     }

 }

I just started to study about JTree. I have created a jtree with entryOID as parent. Actually in backend the entryOID has its parent. Can i get this parant and how can i display it by avoiding the entryOID? Please help?


Solution

  •  private void loadParentMibs throws SQLException () {
    
       ResultSet resultSet = Application.getDBHandler()
         .executeQuery(SQLQueries.SELECT_TABULARMIBS_PARENT);
    
       DefaultMutableTreeNode root = (DefaultMutableTreeNode)getRoot();
    
       Map<String, DefaultMutableTreeNode> parentsMap
         = new HashMap<String, DefaultMutableTreeNode>();
    
       while( resultSet.next() ) {  
         String parentId = resultSet.getString("mt_oid");
    
         DefaultMutableTreeNode parent = parentsMap.get(parentId);
         if ( parent == null ) {
           parent = new DefaultMutableTreeNode( parentId );
           parentsMap.add( parentId, parent );
           root.add( parent );
         }
    
           // Are you sure, you want Boolean.TRUE leafs 
           //   in number of parent coincindence?
           // May be you want leafs to contains some 
           //   additional info from resultSet entity?
         DefaultMutableTreeNode leaf = new DefaultMutableTreeNode(Boolean.TRUE);
         parent.add(leaf);
       }
    
     }