从给定的子节点获取父节点

时间:2012-11-09 06:44:03

标签: java swing jtree treenode

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

 }

我刚刚开始研究JTree。我创建了一个带有entryOID作为父级的jtree。实际上在后端,entryOID有其父级。我可以获得这个parant吗?如何通过避免entryOID来显示它?请帮帮忙?

1 个答案:

答案 0 :(得分:1)

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

 }