Converting a Node in a JTree Component to a TreePath - Java Swing

Java examples for Swing:JTree

Description

Converting a Node in a JTree Component to a TreePath

Demo Code

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class Main {
  // Returns a TreePath containing the specified node.
  public TreePath getPath(TreeNode node) {
    List list = new ArrayList();

    // Add all nodes to list
    while (node != null) {
      list.add(node);/*from  w  w  w  .j a  va 2s.c  o  m*/
      node = node.getParent();
    }
    Collections.reverse(list);

    // Convert array of nodes to TreePath
    return new TreePath(list.toArray());
  }
}

Related Tutorials