problem in Jtree

Hello,

I am creating a JTree and trying to find the depth of a selected node;So I am trying to find the selected node and then get the depth.I am getting it correctly,but after I find it ,tree collapses to root and does not exapnd on clicking.Let me know the error.

import java.awt.Dimension;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import javax.swing.JFrame;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;

publicclass treeTestextends JFrame{

JTree _tree;

public treeTest(){

_tree=new JTree();

_tree.setPreferredSize(new Dimension(200, 600));

_tree.addMouseListener(new MouseListener(){

publicvoid mouseClicked(MouseEvent e){

String ssname;

int depth;

if (e.getSource()instanceof JTree){

try{

ssname = _tree.getSelectionPath()

.getLastPathComponent().toString();

DefaultMutableTreeNode node=(DefaultMutableTreeNode)find(_tree,

(DefaultMutableTreeNode)_tree.getModel().getRoot(),ssname);

depth=node.getDepth();

}catch (Exception exp){

ssname ="novalue";

depth=0;

//_repSel.removeAllItems();

}

if (!(ssname.equals("novalue"))){

//Vector v = getComboData(ssname);

DefaultMutableTreeNode node;

node=find(_tree,(DefaultMutableTreeNode)_tree.getModel().getRoot(),ssname);

depth=node.getDepth();

System.out.println("depth is:"+depth+"for node:"+node);

}

}

}

publicvoid mousePressed(MouseEvent arg0){

// TODO Auto-generated method stub

}

publicvoid mouseReleased(MouseEvent arg0){

// TODO Auto-generated method stub

}

publicvoid mouseEntered(MouseEvent arg0){

// TODO Auto-generated method stub

}

publicvoid mouseExited(MouseEvent arg0){

// TODO Auto-generated method stub

}

});

getContentPane().add(_tree);

pack();

setVisible(true);

}

publicstaticvoid main(String args[]){

new treeTest();

}

public DefaultMutableTreeNode find(JTree _tree,

DefaultMutableTreeNode root, String name){

if (root.getUserObject().equals(name)){

_tree.collapseRow(0);

return root;

}

DefaultMutableTreeNode el =null;

int childCount = root.getChildCount();

DefaultMutableTreeNode child;

for (int i = 0; i < childCount; i++){

child = (DefaultMutableTreeNode) root.getChildAt(i);

el = find(_tree, child, name);

if (el !=null)

return el;

}

return el;

}

}

[5267 byte] By [Sruthi.ma] at [2007-11-26 17:27:17]
# 1
Hello everybody,I got the answer. I can use :DefaultMutableTreeNode node=(DefaultMutableTreeNode)_tree.getSelectionPath().getLastPathComponent();to get the selected node.I am sorry to post the question.Sruthi.
Sruthi.ma at 2007-7-8 23:55:14 > top of Java-index,Desktop,Core GUI APIs...