JTree path

I built a JTree thanks to several DefaultMutableTreeNode, wich were instantiate by:
new DefaultMutableTreeNode ( MyCategory );
MyCategory is an object from a class I made by my self (class CategoryNode)
The snag is, once I have this tree, I retrieve a given CategoryNode, and I must set the selection of my tree so that this CategoryNode is the one that will be selected.
I do not understand how to do it. I tried with the "setSelectionPath(TreePath path) " method, but I do not know how to built the TreePath. I do not understand how it works.
Someone can help me ? Someone as an example of this ?
Thank you very much !
Sylvain.

My english as bad as yours:-))
i'm russian
Just an example of finding suitable node.
import javax.swing.*;
import javax.swing.tree.*;
class Test extends JFrame
public Test()
super("Test");
DefaultMutableTreeNode root=new DefaultMutableTreeNode("ROOT");
DefaultMutableTreeNode n1=new DefaultMutableTreeNode("1");
DefaultMutableTreeNode n2=new DefaultMutableTreeNode("1_1");
n1.add(n2);
String category="founded";
n2=new DefaultMutableTreeNode("1_2");
n1.add(n2);
root.add(n1);
DefaultMutableTreeNode nnnn=new DefaultMutableTreeNode(category);
n2.add(nnnn);
n1=new DefaultMutableTreeNode("2");
root.add(n1);
JTree tree=new JTree(root);
DefaultMutableTreeNode node=findNode(root,category);
tree.setSelectionPath(new TreePath(node.getPath()));
JScrollPane scroll=new JScrollPane(tree);
getContentPane().add(scroll);
setSize(300,300);
setVisible(true);
public DefaultMutableTreeNode findNode(DefaultMutableTreeNode localRoot,Object category) {
DefaultMutableTreeNode resultNode=null;
if (localRoot.getUserObject().equals(category)) {
return localRoot;
int cnt=localRoot.getChildCount();
for (int i=0; i<cnt; i++) {
DefaultMutableTreeNode tempNode=findNode((DefaultMutableTreeNode)localRoot.getChildAt(i),category);
if (tempNode!=null) {
return tempNode;
return resultNode;
public static void main(String a[])
new Test();
best regards
Stas

Similar Messages

  • JTree path selection

    I have a JTree on the left scrollpane and on clicking the value of a node, I display the value in a text field on the right scrollpane. I change the value and set the value in the JTree . I am unable to make the edited tree path selected. The methods provided in the API do not seem to work.

    Don't the JTree.makeVisible( ... ) or JTree.scrollPathToVisible( ... ) methods help?
    kind regards,
    Jos
    Edited by: JosAH on Aug 23, 2009 6:19 PM: typo

  • JTree Path expansion help

    Hi,
    I have made my own jtree to load all the directories in the c drive. I am making a simple windows type browser. I allow users to select a driectory and create a new directory within it. The thing is, once this new directory is created it doesnt show up so i reinitialize the JTree to load all the directories again, and this time the new directory shows up in the directory it was created in. The problem is that before i reinitialize the tree again, i save a treepath for the directory the user is creating a new directory in., but after i reinitialize the tree i need to expand back to that path, i try using expandPath(savedTreePath) but its not working. Any ideas? Code is below.
    private class NewFolderListener implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
                             .getLastSelectedPathComponent();
                   if (selectedNode == null) {
                        System.out.println("New folder not created");
                        return;
                   File temp = (File) selectedNode.getUserObject();
                   String newFolderPath = temp.getAbsolutePath() + "\\" + "New Folder";
                   System.out.println(temp);
                   temp = new File(newFolderPath);
                   temp.mkdir();
                            TreePath tp = new TreePath(selectedNode.getPath);
                   makeTree();
                             tree.expandPath(tp);
    //Reinitialize tree method
    private void makeTree() {
              try {
                   //setLook();
                   tree = new SimpleTree("C:\\");
                   //location.setText("C:\\");
                   splitPane.setLeftComponent(new JScrollPane(tree));
                   tree.addTreeSelectionListener(new TreeSelectionListener() {
                       public void valueChanged(TreeSelectionEvent e) {
                           DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                              tree.getLastSelectedPathComponent();
                           if(node!=null){
                                MyFile mf = (MyFile)node.getUserObject();
                                location.setText(mf.getAbsolutePath());     
                                fselected = mf;
                           makeRightPane();
                   tree.setExpandsSelectedPaths(true);
                   //cp.validate();
              } catch (Exception e) {
         }Anyone have any idea what i am doing wrong?

    Well ive tried using the tree model, calling methods
    such as reload() reload(node) , but none of the
    reloaded the new directory which was created for the
    node.The reload() method is only useful when you have modified existing nodes.
    Use other methods defined in DefaultTreeModel to change tree structure.

  • JTree path question

    I have created a program that basically simulates single celled organisms in a random (non graphical) world, and I want to use a JTree to show the family history and allow the user to bring up an organism's stats by clicking on in the the Jtree, but I have a problem. Each organism has a unique ID number (starting at 0) and that's what I want to display on the tree. I have the code working to add the new organisms to the root, but I want them added as a child to the parent (each child has only one parent for these organisms), but I don't know how to do it. I tried using insertNodeInto but since everything after the root is dynamically generated I don't know how to identify the parent correctly (just using the ID doesn't seem to do anything). Do I need to create a method that somehow copies the entire treemodel into a collection and steps through it? I have the organisms in a collection already (an arraylist to be exact), so I could figure out the lineage by stepping through that, but then how do I build a 'selection path' object that will work to tell Java exactly where I want the child to go? Is the selection path just some kind of array, or is it even possible to build a selection path without a user clicking on a tree node? I hope you can figure out what I'm trying to say here and I appreciate any help you can give.

    Start by creating a Map that has your organisms as the key and the nodes they are in as the value. Or just let the organism include a reference to the node that contains it. Either of those would allow you to identify the TreeNode that contains a particular organism.

  • How to get the JTree path including the rest of its node

    I want to listen for expansion and collapse events in a JTree including the rest of all its children and nodes. Because if the tree have some similar or same nodes at the upper level, it is hard to know which node has been selected. That is why I want to know all its children.
    I think the traditional way can not be implemented.
    JTree tree = (JTree)evt.getSource();
    TreePath path = evt.getPath();
    Does someone has any idea?
    Thank you.

    My code below turns the selected node in a tree into a Complete Window's Style Path:
        //Get the Path
        TreePath path = tree.getSelectionPath();
        String address;
        if (path == null) return;
        address = new String();
        //Convert Path to String: format is [ root , subtree1, node2, child 3] etc
        address = path.toString();
        //Lop first bit off leaving root, subtree1, node2, child 3]
        address = address.substring(1);
        //Convert ", " into "\" character to make root\subtree1\node2\child 3]
        //replaceAll method uses regular expressions - hense \\\\ only equals one
        ///after being processed..
        address = address.replaceAll(", ","\\\\");
        //remove trailing ]
        address = address.replace(']','\\');This may be what your looking for, or alternatively, it may not.
    Hope it helps set you in the right direction.
    Phillip Taylor
    www.geocities.com/PhillipRossTaylor/

  • How to activate mouse right click  on a JTree PATH

    Hi,
    I'm trying to generate a pop menu in a Jtree on mouse event right click.
    So far it is okay, but the problem I have now is to popup the menu only if a precise element of the Jtree is selected.
    Here is some pieces of my code :
    private void fill_panelCenter() {
    stmt.init(conn.getconn());
    ttree.build_root(racine, stmt.getTables(), stmt.getViews(), stmt.getIndexes(), stmt.getPackages(), stmt.getProcedures(), stmt.getFunctions());
    NewTree = new JTree(ttree.getracine());
    NewTree.setBounds(new Rectangle(0, 0, 288, 677));
    trexTree.setVisible(false);
    NewTree.setVisible(true);
    NewTree.addTreeSelectionListener(new TreeSelectionListener(){
    public void valueChanged(TreeSelectionEvent e)
    popup.add("Edit");
    NewTree.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    NewTree_mouseClicked(e);
    jScrollPane1.getViewport().add(NewTree, null);
    panelCenter.add(jScrollPane1, null);
    private void NewTree_mouseClicked(MouseEvent e) {
    if (e.get && e.getButton() == 3) {
    popup.show(e.getComponent(), e.getX(), e.getY());
    }

    Hi,
    Thanks for tip, well i didn't use exactly what was there but it help me
    make my own.
    And i find it a bit more simple so for anybody who that might help :
    NewTree.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (e.getButton() == 3) {
    TreePath path = NewTree.getPathForLocation(e.getX(), e.getY());
    if (path != null) {
    popup.show(NewTree, e.getX(), e.getY());
    Remember to replace NewTree by your own !
    :-D
    Well well I just need to make the path selected now .... I mean after the right click so the user knows which path he has selected.
    Any ideas ?

  • Path in JTree

    How should I know where I click in jTree, actually I want to read the value of the selected node in JTree.
    Thanks
    Raheel

    You can a implement a selection listener and get the node each time a selection is made.
    Or from the API you can glean the method
    Object      getLastSelectedPathComponent()
    Returns the last path component in the first node of the current selection.

  • How to get the path when i select a directory or a file in a JTree

    How to get the path when i select a directory or a file in a JTree

    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.HeadlessException;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Iterator;
    * @author Frederic FOURGEOT
    * @version 1.0
    public class JTreeFolder extends JPanel {
    protected DefaultMutableTreeNode racine;
    JTree tree;
    protected JScrollPane scrollpane;
    final static int MAX_LEVEL = 1; // niveau max de descente "direct" dans l'arborescence
    * Sous-classe FSNode
    * @author Frederic FOURGEOT
    * @version 1.0
    private class FSNode extends DefaultMutableTreeNode {
    File file; // contient le fichier li� au noeud
    * Constructeur non visible
    private FSNode() {
    super();
    * Constructeur par initialisation
    * @param userObject Object
    FSNode(Object userObject) {
    super(userObject);
    * Constructeur par initialisation
    * @param userObject Object
    * @param newFile File
    FSNode(Object userObject, File newFile) {
    super(userObject);
    file = newFile;
    * Definit le fichier lie au noeud
    * @param newFile File
    public void setFile(File newFile) {
    file = newFile;
    * Renvoi le fichier lie au noeud
    * @return File
    public File getFile() {
    return file;
    public JTree getJTree(){
         return tree ;
    * Constructeur
    * @throws HeadlessException
    public JTreeFolder() throws HeadlessException {
    File[] drive;
    tree = new JTree();
    // cr�ation du noeud sup�rieur
    racine = new DefaultMutableTreeNode("Poste de travail");
    // cr�ation d'un noeud pour chaque lecteur
    drive = File.listRoots();
    for (int i = 0 ; i < drive.length ; i++) {
    FSNode node = new FSNode(drive, drive[i]);
    addFolder(drive[i], node); // on descend dans l'arborescence du lecteur jusqu'� MAX_LEVEL
    racine.add(node);
    // Gestion d'evenement sur JTree (on �coute les evenements TreeExpansion)
    tree.addTreeExpansionListener(new TreeExpansionListener() {
    public void treeExpanded(TreeExpansionEvent e) {
    // lorsqu'un noeud est ouvert
    // on descend dans l'arborescence du noeud jusqu'� MAX_LEVEL
    TreePath path = e.getPath();
    FSNode node = (FSNode)path.getLastPathComponent();
    addFolder(node);
    ((DefaultTreeModel)tree.getModel()).reload(node); // on recharche uniquement le noeud
    public void treeCollapsed(TreeExpansionEvent e) {
    // lorsqu'un noeud est referm�
    //RIEN
    // alimentation du JTree
    DefaultTreeModel model = new DefaultTreeModel(racine);
    tree.setModel(model);
         setLayout(null);
    // ajout du JTree au formulaire
    tree.setBounds(0, 0, 240, 290);
    scrollpane = new JScrollPane(tree);
         add(scrollpane);
         scrollpane.setBounds(0, 0, 240, 290);
    * Recuperation des sous-elements d'un repertoire
    * @param driveOrDir
    * @param node
    public void addFolder(File driveOrDir, DefaultMutableTreeNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    addFolder(driveOrDir, node, 0);
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Recuperation des sous-elements d'un repertoire
    * (avec niveau pour r�cursivit� et arr�t sur MAX_LEVEL)
    * @param driveOrDir File
    * @param node DefaultMutableTreeNode
    * @param level int
    private void addFolder(File driveOrDir, DefaultMutableTreeNode node, int level) {
    File[] fileList;
    fileList = driveOrDir.listFiles();
    if (fileList != null) {
    sortFiles(fileList); // on tri les elements
    // on ne cherche pas plus loin que le niveau maximal d�finit
    if (level > MAX_LEVEL - 1) {return;}
    // pour chaque �l�ment
    try {
    for (int i = 0; i < fileList.length; i++) {
    // en fonction du type d'�l�ment
    if (fileList[i].isDirectory()) {
    // si c'est un r�pertoire on cr�� un nouveau noeud
    FSNode dir = new FSNode(fileList[i].getName(), fileList[i]);
    node.add(dir);
    // on recherche les �l�ments (r�cursivit�)
    addFolder(fileList[i], dir, ++level);
    if (fileList[i].isFile()) {
    // si c'est un fichier on ajoute l'�l�ment au noeud
    node.add(new FSNode(fileList[i].getName(), fileList[i]));
    catch (NullPointerException e) {
    // rien
    * Recuperation des sous-elements d'un noeud
    * @param node
    public void addFolder(FSNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    for (int i = 0 ; i < node.getChildCount() ; i++) {
    addFolder(((FSNode)node.getChildAt(i)).getFile(), (FSNode)node.getChildAt(i));
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Tri une liste de fichier
    * @param listFile
    public void sortFiles(File[] listFile) {
    triRapide(listFile, 0, listFile.length - 1);
    * QuickSort : Partition
    * @param listFile
    * @param deb
    * @param fin
    * @return
    private int partition(File[] listFile, int deb, int fin) {
    int compt = deb;
    File pivot = listFile[deb];
    int i = deb - 1;
    int j = fin + 1;
    while (true) {
    do {
    j--;
    } while (listFile[j].getName().compareToIgnoreCase(pivot.getName()) > 0);
    do {
    i++;
    } while (listFile[i].getName().compareToIgnoreCase(pivot.getName()) < 0);
    if (i < j) {
    echanger(listFile, i, j);
    } else {
    return j;
    * Tri rapide : quick sort
    * @param listFile
    * @param deb
    * @param fin
    private void triRapide(File[] listFile, int deb, int fin) {
    if (deb < fin) {
    int positionPivot = partition(listFile, deb, fin);
    triRapide(listFile, deb, positionPivot);
    triRapide(listFile, positionPivot + 1, fin);
    * QuickSort : echanger
    * @param listFile
    * @param posa
    * @param posb
    private void echanger(File[] listFile, int posa, int posb) {
    File tmpFile = listFile[posa];
    listFile[posa] = listFile[posb];
    listFile[posb] = tmpFile;

  • How to get the path of the selected Jtree node for deletion purpose

    I had one Jtree which show the file structure of the system now i want to get the functionality like when i right click on the node , it should be delete and the file also deleted from my system, for that how can i get the path of that component
    i had used
    TreePath path = tree.getPathForLocation(loc.x, loc.y);
    but it gives the array of objects as (from sop)=> [My Computer, C:\, C:\ANT_HOME, C:\ANT_HOME\lib, C:\ANT_HOME\lib\ant-1.7.0.pom.md5]
    i want its last path element how can i get it ?

    Call getLastSelectedPathComponent() on the tree.

  • Path and JTree?

    Hi everybody !!!
    I would like to know how I can get the complete path of the JTree. I use the getLastSelectedPathComponent()) but it display only the folder. Do you know a method that can display the path of the folder?
    tree.addMouseListener(new MouseAdapter()
         public void mousePressed(MouseEvent e)
              if (e.getModifiers()==e.BUTTON1_MASK) // Bouton gauche
                             planche.affichageGraphique(tree.getLastSelectedPathComponent());
              else if(e.getModifiers()==e.BUTTON3_MASK) // Bouton droit
                             f_temps.setVisible(true);
    Thanks !!!

    jTree.getSelectionPath()

  • Problem Expanding certain paths in a JTree

    I am working with a JTree and trying to do the following:
    My JTree is initially defined using the following code:
    rootNode = new DefaultMutableTreeNode();
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    tree = new JTree(treeModel);
    //treeListener = new TreeSelectionListener();
    tree.addTreeSelectionListener(treeListener);
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
    renderer.setLeafIcon(null);
    tree.setCellRenderer(renderer);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setShowsRootHandles(true);
    tree.setAutoscrolls(true);
    tree.setExpandsSelectedPaths(true);
    When a user selects a node, and presses some button, I get and save the current path (of the selected component) like this:
    TreePath currentPath = tree.getSelectionPath();
    Then I do some action on it, then repopulate the JTree
    I have the following code at the bottom of the JTree populating method in an effort to expand the path in the tree which was last selected:
    tree.expandPath(currentPath);
    tree.setVisible(true);
    tree.updateUI();
    The problem is that when the tree repopulates, it stays completely collapsed, and I can't seem to figure out how automatically make it viewable in an expanded state (I don't want the user to have to go expand each expandable node by clicking beside it)
    Does anyone know how to either expand the whole tree from the very beginning, or expand just the selected path?
    Thanks in advance for your help,
    Noha

    To expand on path there is jtree.expandPath(treepath);
    To expand the whole tree, I wrote a recursive method.

  • Jtree; searching node by inserting path name

    Hello,
    I have a jtree which allows me to explore my harddisk.
    The thing I want is finding a directory by inserting a path name ( with a JTextfield).
    I am already able to reveice the inserted path.
    But how do I let the JTree go to that inserted path name?
    For more information, just ask.
    Grtz

    well, if you have the node and are using DefaultTreeModel, you can call: getPathToRoot(TreeNode)
    Not sure how to find the node from the value except to just loop thru the entire tree... or maintain a separate table of value/node objects.

  • Expand a path in JTree

    Hi all. Please help, I am trying to programmatically expand JTree with JTree.expandPath(path), but it only works one level downwards from the last physically selected node. Is this a bug, or am I doing something wrong?

    If you are using DefaultMutableTreeNode for your nodes, thenTreePath tp = new TreePath(theNode.getPath());gets you a path from the root to theNode. If you want that to be the selection, thentheTree.setSelectionPath(tp);and if you want it to be expanded and viewable thentheTree.expandPath(tp);If you aren't using DefaultMutableTreeNode, you will have to build the TreeNode[] that contains the nodes from the root down to theNode by some kind of loop; the rest of the code still works.

  • JTree corruption problem when expanding paths (sometimes)

    Sometimes when adding nodes or expanding paths in my JTree I get a really weird corruption. Here's screenshots of the problem:
    http://linuxhelp.homeunix.com/screen1.png
    http://linuxhelp.homeunix.com/screen2.png
    How can I stop this from happening?
    Adam

    Hi!
    I also had this problem but it works fine using SwingUtilities.invokeLater
    /Malin
    private class ExpandListener implements TreeWillExpandListener {
    TreePath path = null;
    public void treeWillCollapse(TreeExpansionEvent e) {   
    public void treeWillExpand(TreeExpansionEvent e) {
    path = e.getPath();
    collapseAll();
    if (path != null) {
    // If we don't scroll later it doesn't work correctly in some cases
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    scrollPathToVisible(path);
    * Collapses the tree.
    public void collapseAll() {
    for (int i = root.getChildCount(); i > 0; i--) {
    collapseRow(i);

  • Updating Jtree witout loosing selected Path

    Hi,
    I want the user to be able to get the most recent version of the database structure that is represented by the tree, without loosing the selected path.
    that's mean i would like to update the Jtree structure without changing the selected path.
    i tried to use myJtree.getModel.nodeStructureChanged((TreeNode) changedNode) but without success the selcted path is losed.
    Is there any idea?
    Thanks in advance

    no this dosen't work , here after my code:
    DefaultMutableTreeNode addedNode=new DefaultMutableTreeNode("NewNode");
    ParentNode.add(addedNode);
    // and i fired this event to cheng the tree
    ((DefaultTreeModel) myTree.getModel())).nodeStructureChanged((TreeNode) node);
    but with this i lose mu selected Path
    and i also tried this
    ((DefaultTreeModel) myTree.getModel())).nodeChanged((TreeNode) node);
    but no success i can't update my tree structure

Maybe you are looking for

  • Acrobat 9 Pro Extended or Acrobat 3D?

    I have CATIA  v5 r19 and NX 7.0 3d models and I want to put them into Adobe so they can be shared by other downstream users for viewing, however my issue is that I am not sure what software to do this with? I have 9 Pro Extended which does not suppor

  • White mark instead of Image

    Hi. I try to place an image at a panel. Here is the whole program: public class Frame1 extends JFrame { JPanel contentPane; JPanel jPanel1 = new JPanel(); JLabel jLabel1 = new JLabel(); public Frame1() { contentPane = (JPanel) this.getContentPane();

  • Asset management for Plug-ins

    After Effects performs certain kinds of asset management for a project. When you import an image or footage, the project keeps a file-reference to it, sometimes relative. You can "Collect Files..." and gather them all to one place. Handy! Is there an

  • "use ODBC outer join syntax on limits"  issues

    I'm converting a series of BQY's from Brio 6.6 to Hyperion 9.3. I have some questions about the "use ODBC outer join syntax on limits" option in the OCE. I sort of understand this option's purpose, but I don't completely understand the SQL I'm seeing

  • OK, has anyone out there had the same time suck constant problems?  I've had LR now for about 6 months and it has given me more problems than it has been worth.

    Has anyone had the same time suck problems?  Always something.  Couldn't publish to Flickr, now it's FB.  Last batch of images loaded all over exposed.  I didn't touch any settings......I was gone.  I run MAC Yosemite.  Personally I think this progra