DefaultMutableTreeNode, TreePath, setSelection

I have a DefaultMutableTreeNode, and I want that to be selected(highlighted in blue, like if a user clicked on it). I don't know how to convert that to a TreePath so I can use the JTree.setSelection( TreePath ) method.
Are there any suggestions?
Here is my code snippet
JTree tree...
FolderNode...//Special class made by me.
  protected void selectCreatedFolder(String name)
    DefaultMutableTreeNode dt = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
    Enumeration e = dt.children();
    while ( e.hasMoreElements() )
      DefaultMutableTreeNode d =  (DefaultMutableTreeNode)e.nextElement();
      FolderNode fn = (FolderNode)d.getUserObject();
      if ( fn.folderName.equals(name) )
        System.out.println( "Found folder!!! "+name );
//          tree.setSelectionPath(); Needs a Treepath to set it
        fn.expand( d );
        model.reload( d );
        break;
  }

Here is the working code for anyone who may query this thread in the future.
  protected void selectCreatedFolder(String name)
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
    updateTree(parent);//updates the tree
    Enumeration e = parent.children();
    while ( e.hasMoreElements() )
      DefaultMutableTreeNode child =  (DefaultMutableTreeNode)e.nextElement();
      FolderNode fn = (FolderNode)child.getUserObject();
      if ( fn.folderName.equals(name))
        tree.setSelectionPath( new TreePath( child.getPath() ) );
        return;
  }

Similar Messages

  • Drag and Drop - Transferable, how to pass a reference? (URGENT)

    I've a tree that supports drag and drop correctly but every time I exchange a node position the old parent instance remaining on the tree is different from the one I was referencing with the dragged child before the drag occurred. I absolutely need to maintain all references and cannot work with copies.
    Is there any way to use the Transferable interface to pass the original object instead of a copy?
    Thanks to Tedhill who raised the problem, trying to get a quick answer.
    ;o)

    hi guys let me close this thread:
    Thanks to asjf and sergey35 who helped me.
    Actually the isDataFlavorSupported method you suggest passes a reference and not a copy.
    Too bad I fell into another problem with the reloading of the
    moving-node Object after the DnD.
    But finally the working code is:
    public class XJTreeDnD extends XJTree implements DragGestureListener, DragSourceListener, DropTargetListener{
      private DefaultMutableTreeNode dragNode = null;
      private TreePath dragParentPath = null;
      private TreePath dragNodePath = null;
      private DragSource dragSource;
      private DropTarget dropTarget;
      private TransferableTreePath transferable;
      private boolean DnDEnabled = true;
      //private boolean CnPEnabled = false;
      public XJTreeDnD(XNode node) {
        super(node);
        // Set up the tree to be a drop target.
        dropTarget = new DropTarget(this, DnDConstants.ACTION_MOVE, this, true);
        // Set up the tree to be a drag source.
        dragSource = DragSource.getDefaultDragSource();
        dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this);
      private DefaultMutableTreeNode getTreeNode(Point location) {
        TreePath treePath = getPathForLocation(location.x, location.y);
        if (treePath != null) {
          return((DefaultMutableTreeNode) treePath.getLastPathComponent());
        } else {
          return(null);
    //dragGesture implementation
        public void dragGestureRecognized(DragGestureEvent e) {
          if(DnDEnabled){
            TreePath path = this.getSelectionPath();
            if (path == null || path.getPathCount() <= 1) {
              System.out.println("Error: Path null, or trying to move the Root.");
              return;
            dragNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            dragNodePath = path;
            dragParentPath = path.getParentPath();
            transferable = new TransferableTreePath(path);
            // Start the drag.
            e.startDrag(DragSource.DefaultMoveDrop, transferable, this);
    //dragSource implementation
        public void dragDropEnd(DragSourceDropEvent e) {
          try {
            if (e.getDropSuccess()) {
              ((BaseXJTreeModel)this.getModel()).removeNodeFromParent(dragNode);
              DefaultMutableTreeNode dragParent = (DefaultMutableTreeNode) dragParentPath.getLastPathComponent();
              XNode xnodeParent = (XNode)dragParent.getUserObject();
              ((BaseXJTreeModel)this.getModel()).valueForPathChanged(dragParentPath, xnodeParent);
          } catch (Exception ex) {
            ex.printStackTrace();
        public void dragEnter(DragSourceDragEvent e) {
          // Do Nothing.
        public void dragExit(DragSourceEvent e) {
          // Do Nothing.
        public void dragOver(DragSourceDragEvent e) {
          // Do Nothing.
        public void dropActionChanged(DragSourceDragEvent e) {
          // Do Nothing.
    //dropTarget implementation
        public void drop(DropTargetDropEvent e) {
          try {
            Point dropLocation = e.getLocation();
            DropTargetContext dtc = e.getDropTargetContext();
            XJTreeDnD tree = (XJTreeDnD) dtc.getComponent();
            TreePath parentPath = tree.getClosestPathForLocation(dropLocation.x, dropLocation.y);
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
            Transferable data = e.getTransferable();
            DataFlavor[] flavors = data.getTransferDataFlavors();
            for (int i=0;i<flavors.length;i++) {
              if (data.isDataFlavorSupported(flavors)) {
    e.acceptDrop(DnDConstants.ACTION_MOVE);
    TreePath movedPath = (TreePath) data.getTransferData(flavors[i]);
    DefaultMutableTreeNode treeNodeMoved = (DefaultMutableTreeNode) movedPath.getLastPathComponent();
    DefaultMutableTreeNode treeNodeLeft = (DefaultMutableTreeNode) this.dragNodePath.getLastPathComponent();
    XNode xnodeParent = (XNode)parent.getUserObject();
    XNode xnodeChild = (XNode)treeNodeLeft.getUserObject();
    /** @todo check the parent whether to allow the drop or not */
    if(xnodeParent.getPath().startsWith(xnodeChild.getPath())){
    System.out.println("cannot drop a parent node on one of its children");
    return;
    if(xnodeParent.getPath().getPath().equals((xnodeChild.getPath().getParentPath()))){
    System.out.println("node is already child of selected parent");
    return;
    // Add the new node to the current node.
    xnodeParent.addChild(xnodeChild);
    ((BaseXJTreeModel)this.getModel()).valueForPathChanged(parentPath, xnodeParent);
    ((BaseXJTreeModel)this.getModel()).insertNodeInto(treeNodeMoved, parent, parent.getChildCount());
    ((BaseXJTreeModel)this.getModel()).valueForPathChanged(movedPath, xnodeChild);
    e.dropComplete(true);
    } else {
    System.out.println("drop rejected");
    e.rejectDrop();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    } catch (UnsupportedFlavorException ufe) {
    ufe.printStackTrace();
    public void dragEnter(DropTargetDragEvent e) {
    if (isDragOk(e) == false) {
    e.rejectDrag();
    return;
    e.acceptDrag(DnDConstants.ACTION_MOVE);
    public void dragExit(DropTargetEvent e) {
    // Do Nothing.
    public void dragOver(DropTargetDragEvent e) {
    Point dragLocation = e.getLocation();
    TreePath treePath = getPathForLocation(dragLocation.x, dragLocation.y);
    if (isDragOk(e) == false || treePath == null) {
    e.rejectDrag();
    return;
    // Make the node active.
    setSelectionPath(treePath);
    e.acceptDrag(DnDConstants.ACTION_MOVE);
    public void dropActionChanged(DropTargetDragEvent e) {
    if (isDragOk(e) == false) {
    e.rejectDrag();
    return;
    e.acceptDrag(DnDConstants.ACTION_MOVE);
    private boolean isDragOk(DropTargetDragEvent e) {
    /** @todo gestire i casi in cui il drop non sia concesso */
    return (true);
    public void setDragAndDropEnabled(boolean enabled){
    this.DnDEnabled = enabled;
    public boolean isDragAndDropEnabled(){
    return this.DnDEnabled;
    Thanks again.
    flat

  • How could i get the selected node in the JTree

    getLastSelectedPathComponent() �returns the parent node of currenr selected, so how could I get the selected node itself in the JTree
    I will appretiate for any help!

    i think you can get by....
    TreePath treePath = tree.getSelectionPath();
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();

  • How to trigger an ActionListener in different class on click of a tree node

    Hi guyz,
    There are three panels inside my main Frame
    -->TopPanel,MiddlePanel and BottomPanel. I have a tree structure inside a panel. This panel along with couple more panels is in MiddlePanel. My main class is "mainClass.java". Inside that i have an actionListener for a specific button. I need to trigger that actionListener when i click one of the tree nodes in the panel i specified before. The problem is that my MiddlePanel is itself a different ".java" file which is being called in my "mainClass" when a specific button is clicked. There are different buttons in my "mainClass" file and for each one i am creating different MiddlePanels depending on the buttons clicked.
    So, if i click the tree node, i need to remove the MiddlePanel and recreate the MiddlePanel(One that will be created when a different button in the mainClass file is clicked). i.e., i need to trigger the actionListener for that corresponding button. Is there a way to do it?

    use this code to call different panel by selecting tree node.....ok
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.sql.SQLException;
    import javax.swing.event.*;
    class MainTree extends JFrame
    private static final long serialVersionUID = 1L;
         CardLayout cl = new CardLayout();
         JPanel panel = new JPanel(cl);
    public MainTree() throws Exception
    JPanel blankPanel = new JPanel();
    blankPanel.setBorder(BorderFactory.createTitledBorder("Blank Panel"));
    panel.add(blankPanel,"0");
    panel.add(blankPanel,BorderLayout.CENTER);
         panel.setPreferredSize(new Dimension(800, 100));
         setSize(1000, 700);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // getContentPane().setLayout(new GridLayout(1,2));
    getContentPane().setLayout(new BorderLayout());
    ConfigTree test = new ConfigTree();
    DefaultMutableTreeNode mainTree = (DefaultMutableTreeNode)test.buildTree();
    JTree tree = new JTree(mainTree);
    tree.setCellRenderer(new DefaultTreeCellRenderer(){
    private static final long serialVersionUID = 1L;
         public Component getTreeCellRendererComponent(JTree tree,Object value,
    boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus){
    JLabel lbl = (JLabel)super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
    NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)value).getUserObject();
    if(node.icon != null)lbl.setIcon(node.icon);
    return lbl;
    getContentPane().add(new JScrollPane(tree));
    loadCardPanels((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot());
    getContentPane().add(panel,BorderLayout.EAST);
         getContentPane().add(blankPanel,BorderLayout.WEST);
    // getContentPane().add(panel);
    tree.addTreeSelectionListener(new TreeSelectionListener(){
    public void valueChanged(TreeSelectionEvent tse){
    NodeWithID node =(NodeWithID)((DefaultMutableTreeNode)((TreePath)tse.getPath())
    .getLastPathComponent()).getUserObject();
    if(node.nodePanel != null)
    String cardLayoutID = node.ID;
    cl.show(panel,cardLayoutID);
    cl.show(panel,"0");
    public void loadCardPanels(DefaultMutableTreeNode dmtn)
    for(int x = 0; x < dmtn.getChildCount(); x++)
    if(((DefaultMutableTreeNode)dmtn.getChildAt(x)).isLeaf() == false)
    loadCardPanels((DefaultMutableTreeNode)dmtn.getChildAt(x));
    NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)dmtn.getChildAt(x)).getUserObject();
    if(node.nodePanel != null)
    String cardLayoutID = node.ID;
    panel.add(cardLayoutID,node.nodePanel);
    public static void main(String[] args) throws Exception{new MainTree().setVisible(true);}
    class ConfigTree
    public Object buildTree() throws Exception
    NodeWithID n0 = new NodeWithID("HelpDesk","");
    NodeWithID n1 = new NodeWithID("Administrator",n0.nodeName);
    NodeWithID n2 = new NodeWithID("Report Form",n1.nodeName,new Tree().getContentPane());
    NodeWithID n3 = new NodeWithID("Create User",n2.nodeName,new JPanel());
    NodeWithID n4 = new NodeWithID("Unlock User",n2.nodeName,new unlockui().getContentPane());
    NodeWithID n5 = new NodeWithID("List User",n2.nodeName,new JPanel());
    NodeWithID n6 = new NodeWithID("Assign Role",n2.nodeName,new AssignRole());
    NodeWithID n9 = new NodeWithID("Operator",n1.nodeName,new JPanel());
    NodeWithID n10 = new NodeWithID("Create Ticket",n9.nodeName,new JPanel());
    NodeWithID n11 = new NodeWithID("My Ticket",n9.nodeName,new JPanel());
    NodeWithID n12 = new NodeWithID("All Ticket",n9.nodeName,new JPanel());
    NodeWithID n13 = new NodeWithID("Event Viewer",n1.nodeName,new JPanel());
    DefaultMutableTreeNode top = new DefaultMutableTreeNode(n0);
    DefaultMutableTreeNode branch1 = new DefaultMutableTreeNode(n1);
    top.add(branch1);
    DefaultMutableTreeNode node1_b1 = new DefaultMutableTreeNode(n2);
    DefaultMutableTreeNode n1_node1_b1 = new DefaultMutableTreeNode(n3);
    DefaultMutableTreeNode n2_node1_b1 = new DefaultMutableTreeNode(n4);
    DefaultMutableTreeNode n3_node1_b1 = new DefaultMutableTreeNode(n5);
    DefaultMutableTreeNode n4_node1_b1 = new DefaultMutableTreeNode(n6);
    branch1.add(node1_b1);
    branch1.add(n1_node1_b1);
    branch1.add(n2_node1_b1);
    branch1.add(n3_node1_b1);
    branch1.add(n4_node1_b1);
    DefaultMutableTreeNode node4_b1 = new DefaultMutableTreeNode(n9);
    DefaultMutableTreeNode n1_node4_b1 = new DefaultMutableTreeNode(n10);
    DefaultMutableTreeNode n2_node4_b1 = new DefaultMutableTreeNode(n11);
    DefaultMutableTreeNode n3_node4_b1 = new DefaultMutableTreeNode(n12);
    node4_b1.add(n1_node4_b1);
    node4_b1.add(n2_node4_b1);
    node4_b1.add(n3_node4_b1);
    DefaultMutableTreeNode node5_b1 = new DefaultMutableTreeNode(n13);
    branch1.add(node1_b1);
    branch1.add(node4_b1);
    branch1.add(node5_b1);
    return top;
    class NodeWithID
    String nodeName;
    String ID;
    JPanel nodePanel;
    ImageIcon icon;
    public NodeWithID(String nn,String parentName)
    nodeName = nn;
    ID = parentName+" - "+nodeName;
    public NodeWithID(String nn,String parentName,Container container)
    this(nn,parentName);
    nodePanel = (JPanel) container;
    nodePanel.setBorder(BorderFactory.createTitledBorder(ID + " Panel"));
    public NodeWithID(String nn,String parentName,JPanel p, ImageIcon i)
    this(nn,parentName,p);
    icon = i;
    public String toString(){return nodeName;}
    }

  • Problems adding nodes to JTree on runtime

    I have added a popup menu to my tree, and would like to be able to add new nodes by right clicking, so I have this code in my event listener:
    void newFolderFolderPopup_mousePressed(MouseEvent e) {
      System.out.println("WEEEEEEEEEEEEEEEEEEEEEEEE");
      FolderDO folder = new FolderDO("New Folder");
      DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(folder);
      TreePath treePath = foldersTree.getSelectionPath();
      DefaultMutableTreeNode slectedNode = (DefaultMutableTreeNode)treePath.getLastPathComponent();
      treeModel.insertNodeInto(newNode,slectedNode,slectedNode.getChildCount());
      foldersTree.scrollPathToVisible(new TreePath(newNode.getPath()));
    }If the slected node is a leaf, it works just fine every time I do it. But if the selected node has children and it has once been expanded, the new node is not displayed (but something strange is happening to the tree). If however the selected node has children and has not been expanded it works fine...???
    Any ideas?

    I have added a popup menu to my tree, and would like to be able to add new nodes by right clicking, so I have this code in my event listener:
    void newFolderFolderPopup_mousePressed(MouseEvent e) {
      System.out.println("WEEEEEEEEEEEEEEEEEEEEEEEE");
      FolderDO folder = new FolderDO("New Folder");
      DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(folder);
      TreePath treePath = foldersTree.getSelectionPath();
      DefaultMutableTreeNode slectedNode = (DefaultMutableTreeNode)treePath.getLastPathComponent();
      treeModel.insertNodeInto(newNode,slectedNode,slectedNode.getChildCount());
      foldersTree.scrollPathToVisible(new TreePath(newNode.getPath()));
    }If the slected node is a leaf, it works just fine every time I do it. But if the selected node has children and it has once been expanded, the new node is not displayed (but something strange is happening to the tree). If however the selected node has children and has not been expanded it works fine...???
    Any ideas?

  • Select Expanded nodes in JTree

    Hi all,
    In the given tree structure, I want to get a node to be selected, once it is expanded.
    + Folder1
    - Folder2
          |
          |__-Folder3
           |
           |__-Folder4
              |
                |__ file1.docCurrently, if I have Folder1 selected and if I expand Folder2, the selection remains at
    Folder1 itself. I need to change the selection to Folder2.
    Also, I need to get the path of the expanded node . ie; when Folder4 is expanded, I need to
    get Folder4 selected and path has to be obtained as \Folder2\Folder3\Folder4.
    I found this link helpful-- http://forums.sun.com/thread.jspa?messageID=3616726, but there
    also, the path is obtained based on selection and not based on expansion.
    Please help with a solution
    Regards,
    Anees

    AneesAhamed wrote:
    Hi all,
    In the given tree structure, I want to get a node to be selected, once it is expanded.
    + Folder1
    - Folder2
    |
    |__-Folder3
           |
           |__-Folder4
              |
                |__ file1.docCurrently, if I have Folder1 selected and if I expand Folder2, the selection remains at
    Folder1 itself. I need to change the selection to Folder2.
    Also, I need to get the path of the expanded node . ie; when Folder4 is expanded, I need to
    get Folder4 selected and path has to be obtained as \Folder2\Folder3\Folder4.
    I found this link helpful-- http://forums.sun.com/thread.jspa?messageID=3616726, but there
    also, the path is obtained based on selection and not based on expansion.
    Please help with a solution
    Regards,
    AneesTo expand any node you need to "know" it either due to a user's mouse click or inside the code that expands it directly, something like :
    - by mouse click :
    myJTree.addMouseListener(new MouseAdapter()
         public void mouseClicked(MouseEvent e)
              TreePath treePath = getPathForLocation(e.getX(), e.getY());
    });- direct code :
    public void treeWillExpand(TreeExpansionEvent e)
         TreePath treePath = e.getPath();
    }Then you can get the corresponding node from the TreePath :
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();But for a selection this should be enough :
    myJTree.setSelectionPath(treePath);
    myJTree.scrollPathToVisible(treePath);Regards,
    Lara.

  • JTree expanding

    Hi,
    I have a little problem with expanding JTree. I have created UI with levelbuttons, which sould expand jTree to next sublevel and collapse jTree back to higher level. The first time I press the expanding button all works fine, because I can set all the rows I want to expand, in this case all rows with addSelectionInterval method ( addSelectionInterval(0, jTree.getRowCount()) ). The problem is, how do I know the rows of next sublevel to expand. Collapsing the current sublevel rows is also a problem. How can get the row indexes of current level?

    Can you put your code here?
    The following may be a solution:
    TreePath treepath =tree.getPathForRow(int row) ; // row is the one you know;
      DefaultMutableTreeNode node=(DefaultMutableTreeNode)(treepath.getLastPathComponent());
      DefaultMutableTreeNode childnode = node.getFirstChild();
      tree.expandPath(new TreePath(childnode.getPath()));

  • Gui object dead in permanet memory

    Hi!
    I created a gui in java for monitoring some applications and this gui update its content each 15 seconds.
    The strange thing I notice is that at each refresh the memory allocated by this gui groves and is never relased! I investigated and using tools like jconsole and jmap I discovered that the problem is in the permanet generation handled by the garbage collector.
    I tried with all the possible existing carbage colletion and I did't find any improvements.
    I am wondering why in the output of jmap I found always a lot of sun/reflect/DelegatingClassLoader marked as dead, and even if I manually perform a garbage collection with jconsole, the gc never clean them!
    Can anyone help me? Can anyone give me any suggestion? Thanks!!!

    the application is a package with a lot of classes. The class that has this problem is this one:
    It use an object called Tupla which is an object with some Strings and two vector, on of which contains others tuplas objects.
    public class SMSTree extends JPanel implements TreeSelectionListener, TreeModelListener, TreeExpansionListener {
         private JPanel nodePane;
         private JTable tableInfo;
         private JTable tableData;
         private SimpleTableModel stmI;
         private SimpleTableModel stmD;
         private JScrollPane infoScroll;
         private JScrollPane dataPanel;
         private JLabel currTime;
        private JTree tree;
        private TreePath treePath = null;
        private String[] path;
        private static boolean playWithLineStyle = false;
        private static String lineStyle = "Horizontal";
        private Vector tp = new Vector();
        DefaultMutableTreeNode top ;
        DefaultTreeModel treeModel;
        public SMSTree(Vector c) {
            super(new GridLayout(1,0));
            Dimension minimumSize = new Dimension(100, 50);
            //Create the nodes.
            top = new DefaultMutableTreeNode("SMS Processes Tree");
            treeModel = new DefaultTreeModel(top);
            treeModel.addTreeModelListener(this);
            createNodes(top, c);
            //Create a tree that allows one selection at a time.
            tree = new JTree(treeModel);
            tree.setPreferredSize(new Dimension(250,700));
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
            tree.addTreeExpansionListener(this);
             tree.setCellRenderer(new SMSTreeRenderer());
             tree.setLargeModel(true);
             tree.setRowHeight( 20 );
             tree.repaint();
            if (playWithLineStyle) {
                System.out.println("line style = " + lineStyle);
                tree.putClientProperty("JTree.lineStyle", lineStyle);
            nodePane = new JPanel();
            nodePane.setVisible(true);
            tableInfo = new JTable();
            tableData = new JTable();
            infoScroll = new JScrollPane(tableInfo);
            JPanel datePanel = new JPanel();
            dataPanel = new JScrollPane(tableData);
            infoScroll.setPreferredSize(new Dimension(650,200));
            infoScroll.setMinimumSize(minimumSize);
            infoScroll.setBackground(new Color(255,223,203));
            tableInfo.setBackground(new Color(255,223,203));
            tableData.setPreferredScrollableViewportSize(new Dimension(650,420));
            tableInfo.setPreferredScrollableViewportSize(new Dimension(680,192));
            tableInfo.setPreferredSize(new Dimension(680,192));
            tableInfo.setMinimumSize(new Dimension(680,192));
            tableInfo.setMaximumSize(new Dimension(10000,192));
            tableData.setPreferredSize(new Dimension(680,413));
            tableData.setMinimumSize(new Dimension(680,413));
            dataPanel.setPreferredSize(new Dimension(650,420));
            dataPanel.setMinimumSize(minimumSize);
            dataPanel.setBackground(new Color(240,255,3));
            tableData.setBackground(new Color(240,255,3));
            datePanel.setPreferredSize(new Dimension(650,25));
            datePanel.setSize(new Dimension(650,25));
            datePanel.setMinimumSize(minimumSize);
            datePanel.setBackground(new Color(255,157,3));
            infoScroll.setBorder(BorderFactory.createTitledBorder(
                      BorderFactory.createCompoundBorder(
                              BorderFactory.createRaisedBevelBorder(),
                              BorderFactory.createLoweredBevelBorder()), "Info Table",
                     TitledBorder.CENTER,
                     TitledBorder.ABOVE_TOP, new Font("Serif", Font.BOLD, 16))
            datePanel.setBorder(BorderFactory.createTitledBorder(
                        BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Last Refresh",
                        TitledBorder.LEFT,
                        TitledBorder.TOP, new Font("Serif", Font.BOLD, 12))
            dataPanel.setBorder(BorderFactory.createTitledBorder(
                      BorderFactory.createCompoundBorder(
                              BorderFactory.createRaisedBevelBorder(),
                              BorderFactory.createLoweredBevelBorder()), "Data Table",
                     TitledBorder.CENTER,
                     TitledBorder.ABOVE_TOP, new Font("Serif", Font.BOLD, 16))
            Date d = new Date();
            currTime = new JLabel(d.toString());
            currTime.setForeground(new Color(3,15,255));
            currTime.setFont(new Font("Serif", Font.BOLD, 14));
            datePanel.add(currTime);
            nodePane.setLayout(new SpringLayout());
            nodePane.add(infoScroll);
            nodePane.add(datePanel);
            nodePane.add(dataPanel);
            nodePane.setBackground(new Color(255,242,234));
            SpringUtilities.makeCompactGrid(nodePane,
                    3 , 1,       //rows, cols
                    6, 6,        //initX, initY
                    6, 6);       //xPad, yPad
            initNodePane();
            tree.setBackground(new Color(255,242,234));
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
            JScrollPane nodeView = new JScrollPane(nodePane);
            tree.setPreferredSize(new Dimension(300,700));
            treeView.setMinimumSize(minimumSize);
            nodeView.setMinimumSize(minimumSize);
            treeView.setPreferredSize(new Dimension(300,700));
            nodeView.setPreferredSize(new Dimension(724,700));
            nodeView.setBackground(Color.white);
            //Add the scroll panes to a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
            splitPane.setLeftComponent(treeView);
            splitPane.setRightComponent(nodeView);
            splitPane.setDividerLocation(300 + splitPane.getInsets().left);
            splitPane.setContinuousLayout(true);
            splitPane.setResizeWeight(1.0);
            splitPane.setBackground(new Color(255,242,234));
            splitPane.setPreferredSize(new Dimension(1024, 768));
            //Add the split pane to this panel.
            add(splitPane);
        /** Required by TreeSelectionListener interface. */
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if (node == null) return;
            treePath = new TreePath(node.getPath());
            Object nodeInfo = node.getUserObject();
            if (nodeInfo instanceof Tupla) {
                 Tupla t = (Tupla)nodeInfo;
                 displayNode(t);
        private void initNodePane() {
            displayNode(null);
        private void displayNode(Tupla node) {
            try {
                if (node != null) {
                     String[] data = node.getContent(true).split(",");
                     Vector colNamesInfo = new Vector();
                     Vector colValuesInfo = new Vector();
                     Vector colNamesData = new Vector();
                     Vector colValuesData = new Vector();
                     for (int i=0; i<data.length; i++){
                          String titleTmp = data.substring(0, data[i].indexOf("=")).trim();
              String value = data[i].substring(data[i].indexOf("=")+1, data[i].length()).trim();
              String title = titleTmp.split(Configuration.typeSep)[0];
              String type = titleTmp.split(Configuration.typeSep)[1];
              if (type.compareTo("info")==0) {
                   colNamesInfo.add(title);
              colValuesInfo.add(value);
              else {
                   colNamesData.add(title);
              colValuesData.add(value);
         if (node.getChildrenContent().size() >0 ){
              Vector c = node.getChildrenContent();
              for (int i=0; i<c.size(); i++){
                   String[] data1 = ((String)c.elementAt(i)).split(",");
         for (int j=0; j<data1.length; j++){
              String titleTmp = data1[j].substring(0, data1[j].indexOf("=")).trim();
              String value = data1[j].substring(data1[j].indexOf("=")+1, data1[j].length()).trim();
              String title = titleTmp.split(Configuration.typeSep)[0];
              String type = titleTmp.split(Configuration.typeSep)[1];
              if (type.compareTo("info")==0) {
                   colNamesInfo.add(title);
              colValuesInfo.add(value);
              else {
                   colNamesData.add(title);
              colValuesData.add(value);
         Vector v = new Vector();
         v.add(colNamesInfo);
         v.add(colValuesInfo);
         stmI = new SimpleTableModel(v, false);
         synchronized (tableInfo){
              EventQueue.invokeLater(new Runnable(){
                   public void run(){
                        int max = tableInfo.getColumnCount();
              for (int i=0; i<max; i++)
                   removeColumnAndData(tableInfo, 0);
              tableInfo.setAutoCreateColumnsFromModel(false);
              tableInfo.setModel(stmI);
              for (int i=0; i<stmI.getColumnCount(); i++){
                   DefaultTableCellRenderer renderer = new ColoredTableCellRenderer();
                   renderer.setHorizontalAlignment(JLabel.LEFT);
                   TableColumn column = new TableColumn(i,200, renderer, null);
                   column.setResizable(true);
                   tableInfo.addColumn(column);
         infoScroll.repaint();
         v = new Vector();
         v.add(colNamesData);
         v.add(colValuesData);
         stmD = new SimpleTableModel(v, false);
         synchronized (tableData) {
              EventQueue.invokeLater(new Runnable(){
                   public void run(){
                        int max = tableData.getColumnCount();
              for (int i=0; i<max; i++)
                   removeColumnAndData(tableData, 0);
              tableData.setAutoCreateColumnsFromModel(false);
              tableData.setModel(stmD);
              for (int i=0; i<stmD.getColumnCount(); i++){
                   DefaultTableCellRenderer renderer = new ColoredTableCellRenderer();
                   renderer.setHorizontalAlignment(JLabel.LEFT);
                   TableColumn column = new TableColumn(i,200, renderer, null);
                   tableData.addColumn(column);
         dataPanel.repaint();
         tableInfo.repaint();
         tableData.repaint();
         nodePane.repaint();
    } else {
         SimpleTableModel stm = new SimpleTableModel(new Vector(), false);
         tableInfo.setAutoCreateColumnsFromModel(true);
         tableInfo.setModel(stm);
         tableData.setAutoCreateColumnsFromModel(true);
         tableData.setModel(stm);
    if (Brain.c.debug > 0) {
    System.out.println("Attempted to display a null Node.");
    } catch (Exception e) {
         e.printStackTrace();
    System.err.println("Attempted to read a bad Node: " + node);
    private void createNodes(DefaultMutableTreeNode top, Vector c) {
    DefaultMutableTreeNode node = null;
    for (int i=0; i<c.size(); i++){
         Tupla t=((Tupla)c.elementAt(i));
              node=new DefaultMutableTreeNode(t);
         if (t.getMyChildren().size()>0){
              if (((Tupla)(t.getMyChildren().elementAt(0))).getMyChildren().size()==0){
                   try {
                        t.setChildrenContent();
                   catch (Exception ex){
                        ex.printStackTrace();
              else {
              createNodes(node, t.getMyChildren());
         top.add(node);
         if (treePath != null) {
              DefaultMutableTreeNode nodeTmp = (DefaultMutableTreeNode)treePath.getLastPathComponent();
              Object nodeInfo = nodeTmp.getUserObject();
              if (nodeInfo instanceof Tupla ){
                   Tupla tTmp = (Tupla)nodeInfo;
                   if (tTmp.getName().compareTo(t.getName())==0){
              String[] tmpList = treePath.toString().split(",");
              for (int j=0; j<tmpList.length; j++){
                   tmpList[j] = tmpList[j].trim();
                   if (tmpList[j].startsWith("[")) tmpList[j]=tmpList[j].substring(1,tmpList[j].length());
                   if (tmpList[j].endsWith("]")) tmpList[j]=tmpList[j].substring(0,tmpList[j].length()-1);
              path = tmpList;
    public void loadData(Vector c){
         top.removeAllChildren();
         treeModel.reload();
         tree.setLargeModel(true);
         tree.setRowHeight( 20 );
         createNodes(top,c);
         if ((treePath != null) && (path != null) && (path.length > 0)) {
              treePath=findByName(tree, path);
              tree.expandPath(treePath);
              tree.setSelectionPath(treePath);
         if (tp!=null){
              for (int i=0; i<tp.size(); i++){
                   //System.err.println("TP "+tp.elementAt(i));
                   String[] tmpList = ((TreePath)tp.elementAt(i)).toString().split(",");
                   for (int j=0; j<tmpList.length; j++){
                   tmpList[j] = tmpList[j].trim();
                   if (tmpList[j].startsWith("[")) tmpList[j]=tmpList[j].substring(1,tmpList[j].length());
                   if (tmpList[j].endsWith("]")) tmpList[j]=tmpList[j].substring(0,tmpList[j].length()-1);
                   TreePath tpT = findByName(tree, tmpList);
                   tree.expandPath(tpT);
         tree.setCellRenderer(new SMSTreeRenderer());
         tree.repaint();
         //treeModel.reload();
         currTime.setText(new Date().toString());
    // Finds the path in tree as specified by the array of names. The names array is a
    // sequence of names where names[0] is the root and names[i] is a child of names[i-1].
    // Comparison is done using String.equals(). Returns null if not found.
    public TreePath findByName(JTree tree, String[] names) {
    TreeNode root = (TreeNode)tree.getModel().getRoot();
    return find2(new TreePath(root), names, 0, true);
    private TreePath find2(TreePath parent, Object[] nodes, int depth, boolean byName) {
    TreeNode node = (TreeNode)parent.getLastPathComponent();
    Object o = node;
    // If by name, convert node to a string
    if (byName) {
    o = o.toString();
    // If equal, go down the branch
    if (((String)o).compareTo((String)nodes[depth])==0) {
         // If at end, return match
    if (depth == nodes.length-1) {
    return parent;
    // Traverse children
    if (node.getChildCount() >= 0) {
         for (Enumeration e=node.children(); e.hasMoreElements(); ) {
    TreeNode n = (TreeNode)e.nextElement();
    TreePath path = parent.pathByAddingChild(n);
    TreePath result = find2(path, nodes, depth+1, byName);
    // Found a match
    if (result != null) {
    return result;
    // No match at this branch
    return null;
    // Removes the specified column from the table and the associated
    // call data from the table model.
    public void removeColumnAndData(JTable table, int vColIndex) {
    SimpleTableModel model = (SimpleTableModel)table.getModel();
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int columnModelIndex = col.getModelIndex();
    Vector data = model.getDataVector();
    // Remove the column from the table
    table.removeColumn(col);
    // Remove the column header from the table model
    // colIds.removeElementAt(columnModelIndex);
    // Remove the column data
    for (int r=0; r<data.size(); r++) {
    Vector row = (Vector)data.get(r);
    if (row.size()>columnModelIndex) {
         row.removeElementAt(columnModelIndex);
    model.setDataVector(data);
    // Correct the model indices in the TableColumn objects
    // by decrementing those indices that follow the deleted column
    Enumeration en = table.getColumnModel().getColumns();
    for (; en.hasMoreElements(); ) {
    TableColumn c = (TableColumn)en.nextElement();
    if (c.getModelIndex() >= columnModelIndex) {
    c.setModelIndex(c.getModelIndex()-1);
    model.fireTableDataChanged();
    model.fireTableStructureChanged();
    public void treeNodesChanged(TreeModelEvent e){
    public void treeNodesInserted(TreeModelEvent e){
    public void treeNodesRemoved(TreeModelEvent e){
    public void treeStructureChanged(TreeModelEvent e){
    // Required by TreeExpansionListener interface.
    public void treeExpanded(TreeExpansionEvent e) {
    //System.err.println("Tree-expanded event detected "+e);
    TreePath tpT = e.getPath();
    if (!tp.contains(tpT)) tp.add(tpT);
    // Required by TreeExpansionListener interface.
    public void treeCollapsed(TreeExpansionEvent e) {
         //System.err.println("Tree-collapsed event detected "+e);
         TreePath tpT = e.getPath();
         if (tp.contains(tpT)) tp.remove(tpT);

  • Getting TreePath from DefaultMutableTreeNode

    Hi,
    I am looking through the APIs and I haven't found a way in which I can get the TreePath of a specific DefaultMutableTreeNode. In the class that I am trying to get this value I have the reference to the JTree in which the node is located, and a reference to the node itself.
    Please let me know if there is a way to get this value...
    P.S. I need this value, to set the JTree focus on the node. So, if you have a solution for that as well, without using the TreePath, it would be of great value also.
    Thankx
    Juan

    Well, just in case someone is watching this post...
    I found a way, it may not be the best but here it goes;
    public void setFocus(JTree tree, DefaultMutableTreeNode node) {
         DefaultMutableTreeNode parent= null;
         int nodeLevel= node.getLevel();
         int indx= 0;
         for( int i= 1; i < nodeLevel; i++ ) {
              parent= (DefaultMutableTreeNode)node.getParent();
              indx+= parent.getIndex(node)+1;
              node= parent;
         tree.setSelectionRow(indx);
         tree.requestDefaultFocus();
    }

  • How can I use an invisible method  in TreePath??

    Dear Friends:
    I hope to use TreePath in following program to create another new TreePath with updated Object.
    in following statement:
    TreePath newObject = new TreePath(tree.getSelectionPath(),"NewPathHere");
    I hope to keep same TreePath, but with new info.
    anything wrong??
    But it gets error:
    The constructor TreePath(TreePath, Object) is not visible
    Here the method is protected, I extends this TreePath class,
    Why I cannot use this method to create a new TreePath with updated Info??
    Regards
    sunny
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class JTreeTraverse extends TreePath{
      public static void main(String args[]) {
        JFrame fm = new JFrame("JTree Traverse frame");
        String object[] = { "Cricket", "Hokey", "Football" };
        JTree tree = new JTree(object);
        tree.setRootVisible(true);
        TreeModel treemodel = tree.getModel();
        Object TraverseObject = treemodel.getRoot();
        if ((TraverseObject != null) && (TraverseObject instanceof
                     DefaultMutableTreeNode)) {
        TreeSelectionListener treeListener = new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            JTree tree = (JTree) treeSelectionEvent.getSource();
            TreePath object = tree.getSelectionPath();
            System.out.println(object);
            System.out.println(object.getPath());
            TreePath newObject = new TreePath(tree.getSelectionPath(),"NewPathHere");
            System.out.println(object);
            System.out.println(object.getPath());
        tree.addTreeSelectionListener(treeListener);
        JScrollPane scroll = new JScrollPane(tree);
        fm.getContentPane().add(scroll, BorderLayout.CENTER);
        fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fm.setSize(200, 200);
        fm.setVisible(true);
    }

    Dear Friends:
    I hope to use TreePath in following program to create another new TreePath with updated Object.
    in following statement:
    TreePath newObject = new TreePath(tree.getSelectionPath(),"NewPathHere");
    I hope to keep same TreePath, but with new info.
    anything wrong??
    But it gets error:
    The constructor TreePath(TreePath, Object) is not visible
    Here the method is protected, I extends this TreePath class,
    Why I cannot use this method to create a new TreePath with updated Info??
    Regards
    sunny
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class JTreeTraverse extends TreePath{
      public static void main(String args[]) {
        JFrame fm = new JFrame("JTree Traverse frame");
        String object[] = { "Cricket", "Hokey", "Football" };
        JTree tree = new JTree(object);
        tree.setRootVisible(true);
        TreeModel treemodel = tree.getModel();
        Object TraverseObject = treemodel.getRoot();
        if ((TraverseObject != null) && (TraverseObject instanceof
                     DefaultMutableTreeNode)) {
        TreeSelectionListener treeListener = new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            JTree tree = (JTree) treeSelectionEvent.getSource();
            TreePath object = tree.getSelectionPath();
            System.out.println(object);
            System.out.println(object.getPath());
            TreePath newObject = new TreePath(tree.getSelectionPath(),"NewPathHere");
            System.out.println(object);
            System.out.println(object.getPath());
        tree.addTreeSelectionListener(treeListener);
        JScrollPane scroll = new JScrollPane(tree);
        fm.getContentPane().add(scroll, BorderLayout.CENTER);
        fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fm.setSize(200, 200);
        fm.setVisible(true);
    }

  • Are TreePaths only valid in the TreeModel they originate from?

    I've got a JTree that lists our warehouse inventory, grouped by primary and secondary invenotry categories. (IE. "Printers" / "Laser" / "SomeLaserPrinter". ) The tree is populated through a SQL query.
    I've got a checkbox that, when the value changes, decides if the tree should show or hide inventory categories that don't contain any inventory items at the moment.
    What happens when I check/uncheck the box is that the tree is rebuilt from scratch according to it's value.
    Now, if there is something selected in the tree when I click that checkbox, I want the same item to be selected and expanded when the tree is rebuilt. This is where I've been running in to problems.
    The ActionListener for the checkbox is as follows:
    //hideEmptyNodes is the JCheckBox
    hideEmptyNodes.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent e ) {
           try { //inventoryTree is the tree
                TreePath tp = inventoryTree.getSelectionPath();
                 // the InventoryTree.fillWithInventory(boolean hideEmpty) method
                 // clears and populates the tree from a SQL query.
           inventoryTree.fillWithInventory( hideEmptyNodes.isSelected() );
                inventoryTree.expandPath(tp);
                inventoryTree.setSelectionPath(tp);
         } catch ( SQLException ex ) {
           LGRUtils.debugErrln( "Error filling tree." );
        } );This, does NOT work, for some reason. I tried creating the TreePath from the new TreeModel, but still the same:
    hideEmptyNodes.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent e ) {
         try { //inventoryTree is the tree
              Object o = inventoryTree.getLastSelectedPathComponent();
               // the InventoryTree.fillWithInventory(boolean hideEmpty) method
               //clears and populates the tree from a SQL query.
           inventoryTree.fillWithInventory( hideEmptyNodes.isSelected() );
              TreePath tp = new TreePath(
                  ((DefaultTreeModel)inventoryTree.getModel())
                  //SimpleTreeNode extends DefaultMutableTreeNode and only
                  //overrides the boolean equals(Object) method.
                  .getPathToRoot((SimpleTreeNode)o));
              inventoryTree.setSelectionPath(tp);
         } catch ( SQLException ex ) {
           LGRUtils.debugErrln( "Error filling tree." );
        } );Quite frankly, I'm at a loss to how this stuff works. I've searched a bit around the forums, and I've found plenty of other people who have problems with setting the selection paths of trees. None of them have gotten their problems solved in any uniform way, it seems the solution varies from user to user.
    Any pointers to a way of doing this, and making it work, would be greatly appreciated!
    -christig

    First thing I would tell you is that if you will not rebuild a tree from scratch, you will not have this problem!
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • DefaultMutableTreeNode to XML file

    Morning all, i have a program that writes a node to an xml file.
    it looks like so:
    public void write(DefaultMutableTreeNode root) {
         try {
         DocumentBuilderFactory factory =   DocumentBuilderFactory.newInstance();
                         DocumentBuilder builder = factory.newDocumentBuilder();
         //now to create the document object that will house the tree.
         Document doc = builder.newDocument();
         Element documentRoot = (Element) root;
         //Add the root element to the document tree.
         doc.appendChild(documentRoot);
         //Output the DOM tree.
         //Create the necessary transformers.
         TransformerFactory transformerFactory =    TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         //transform the DOM tree to output XML file.
         transformer.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("testfile.xml")));
         }catch(Exception e) {          
              e.printStackTrace();
    }im trying to cast my defaultmutabletreenode to an element or some sort of argument that the Document constructor can take.i want to write the hierarchy i have in the DefaultMutableTreeNode to an xml file. Note that this node is a root node.I cant seem to find a solution in the api's, has anyone any ideas?
    Many thanks

    its ok, i found out it cant be done.a bold statetment! ;)
    there are various ways using TreePath to get the hierarchy of a given node. the node, as you found out, does not contain the hierarchy. but if you are talking about the root node, your statement probably is right (what hieracht should have in the first place ;).
    thomas

  • Really interesting bizarre bug in TreePath, I'm confused beyond belief

    Inside a large program, in which I use custom TreeModel instead of DefaultMutableTreeNode's etc, I have a following method which needs to recurse up a TreePath.
    This seems to be a MAJOR bug, because if you look in the following ten lines, I verify several times that the argument is non-null (and even return early if it is).
    However, at the line "while( ... )" it throws a NullPointerException! What, is the keyword "while" null ???!?!?! Because we know that tp is NOT null.
    We also know that we can call "tp.getPathCount()" because I do so and even print it out!#
    If you have any thoughts, please CC to [email protected], because at the moment I'm sure Sun will refuse a bug report (without more info) and I doubt I can make a small program that demonstrates this - otherwise surely it would have been found before!
    public static Hashtable getMapping( TreePath tp )
    System.out.println( "tp = "+tp );
    Hashtable rc = new Hashtable();
    if( tp.getPathCount() > 0 )
    else
    return rc;
    System.out.println( "tp = "+tp );
    int tpcount = tp.getPathCount();
    System.out.println( "tp.count = "+tp.getPathCount() );
    while( tp.getPathCount() > 0 )
    return rc;
    }

    Oh dear. After prolonged testing, I realised the problem: when the TreePath is the root, it returns null as parent , which happens just before I do the test as to whether to carry on - I had originally put the test just before that, but had moved it to just afterwards, thereby causing the problem!
    Very foolish, really.

  • Expand a TreePath in a JTree

    hi
    i face a really strange problem at the moment.
    from my main tree, i want to copy the selected TreePath to my tree in a dialog.
    so i pass the TreePath to the dialog and call the following method:
    tree.expandPath(path);in the tree-initialization i set setExpandsSelectedPaths to true, so the path should be expanded.
    nothing happens.
    either no effect if i call directly expandPath().
    does anybody have an idea why this happen like this?
    thx & greetz
    swissManu

    Hi,
    if I cought your problem, this method should help you. I use it to expand the tree.
    private void expand(JTree tree, DefaultMutableTreeNode node) {
              if (!node.getAllowsChildren()) {
                   return;
              tree.expandPath(new TreePath(node.getPath()));
              for (int step = 0; step < node.getChildCount(); step++) {
                   expand(tree, (DefaultMutableTreeNode)node.getChildAt(step));
         }you can call the method like this:
    expand(tree, (DefaultMutableTreeNode)tree.getModel().getRoot());, tree is an instance of JTree class :-)
    LP

  • How to get TreePath from TreeNode?

    I want to get treepath object of the jtree from one treenode of the jtree.
    But i do not find this method from api.
    If likes following :
    treeNode is the jTree's TreeNode object.
    then
    TreePath path=new TreePath(treeNode);
    Whether the "path" is the object of the jTree?(I think the "path" is not the object of the jTree's one treepath because the "new" .That will be a new object.)
    if not ,is there another method tosolve it?
    Thank's for help?

    just get the code from the DefaultMutableTreeNode object
          * Returns the path from the root, to get to this node.  The last
          * element in the path is this node.
          * @return an array of TreeNode objects giving the path, where the
          *         first element in the path is the root and the last
          *         element is this node.
        public TreeNode[] getPath() {
         return getPathToRoot(this, 0);
         * Builds the parents of node up to and including the root node,
         * where the original node is the last element in the returned array.
         * The length of the returned array gives the node's depth in the
         * tree.
         * @param aNode  the TreeNode to get the path for
         * @param depth  an int giving the number of steps already taken towards
         *        the root (on recursive calls), used to size the returned array
         * @return an array of TreeNodes giving the path from the root to the
         *         specified node
        protected TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
         TreeNode[]              retNodes;
         /* Check for null, in case someone passed in a null node, or
            they passed in an element that isn't rooted at root. */
         if(aNode == null) {
             if(depth == 0)
              return null;
             else
              retNodes = new TreeNode[depth];
         else {
             depth++;
             retNodes = getPathToRoot(aNode.getParent(), depth);
             retNodes[retNodes.length - depth] = aNode;
         return retNodes;
        }

Maybe you are looking for