Solved

Jtree implementation - based on structure given

Posted on 2008-10-07
49
950 Views
Last Modified: 2013-11-23
Hi all,
I am trying to develop a tree in the following structure.

+ Folder1
+ Folder2
+ Folder3
|
|
+ Folder'n'
|
|_File 1
|_File 2
|
|_File 'n'


I have all those folder names inside a vector and file names inside another vector. The folders can or cannot have children.
How to implement this?
I made a thorough study from http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display
and refeered and modified the examples given there to suit my requirements, unfortunately nothing seems to work for me properly(according to my requirement above). If needed I will post the stupid codes developed by me.
Please provide some tips, links or codes based on which i can develop the rest.
Regards,
Anees
0
Comment
Question by:Sreejith22
  • 25
  • 24
49 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 22666773
>> If needed I will post the stupid codes developed by me.
Please do that.
0
 

Author Comment

by:Sreejith22
ID: 22667044

import java.util.Vector;
 

import javax.swing.JFrame;

import javax.swing.JTree;

import javax.swing.event.TreeModelListener;

import javax.swing.tree.TreeModel;

import javax.swing.tree.TreePath;

public class FileTreeFrame extends JFrame {

  private JTree fileTree;
 

  private FileSystemModel fileSystemModel;
 

 

  public FileTreeFrame(String abc) {

    super("JTree FileSystem Viewer");

    Vector names = new Vector();

    names.add("aa");

    names.add("bb");

    names.add("cc");

    names.add("dd");

    names.add("ee");

    names.add("ff");

    fileSystemModel = new FileSystemModel(names);

    fileTree = new JTree(fileSystemModel);

    getContentPane().add(fileTree);

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setSize(640, 480);

    setVisible(true);

  }
 

  
 

  public static void main(String args[]) {

    new FileTreeFrame("");

  }

}
 

class FileSystemModel implements TreeModel {

  private Vector name = new Vector();
 

  private Vector listeners = new Vector();
 

  public FileSystemModel(Vector name) {

	  this.name = name;

	  for(int i=0;i<name.size();i++){

	    	System.out.println(name.elementAt(i));

	    }

  }
 

  public Object getRoot() {

    return name;

  }
 

//THIS METHOD NEED TO RETURN NAME OF CHILD ONLY WHEN THE PARENT DIRECTORY IS EXPANDED RT?

  public Object getChild(Object parent, int index) {

    Vector name = (Vector) parent;

    for(int i=0;i<name.size();i++){

    	System.out.println(name.elementAt(i));

    }

    //THE LOGIC TO BE ADDED HERE IS - CHECK WHETHER name.elementAt(i) IS A DIRECTORY. IF YES RETURN EACH STRING FROM HERE WHICH ARE CHILDREN OF THIS DIRECTORY.IF NOT A DIRECTORY WHAT HAS TO BE DONE

  }
 
 

  public int getChildCount(Object parent) {

    return 0;

  }
 

  public boolean isLeaf(Object node) {

    return  false;

  }
 

  public int getIndexOfChild(Object parent, Object child) {

    

    return -1;
 

  }
 

  public void valueForPathChanged(TreePath path, Object value) {}
 

  private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {}
 

  public void addTreeModelListener(TreeModelListener listener) {}
 

  public void removeTreeModelListener(TreeModelListener listener) {}
 

}

Open in new window

0
 
LVL 37

Expert Comment

by:zzynx
ID: 22667964
>> and file names inside another vector
I don't see that in your code...
0
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 22669220
Try to run this code. I think it is what you want.
Don't hesitate to ask question about it.



File FileTreeFrame.java
================
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JTree;
public class FileTreeFrame extends JFrame {
  private JTree fileTree;
 
  private FileSystemModel fileSystemModel;
 
 
  public FileTreeFrame(String abc) {
    super("JTree FileSystem Viewer");
   
    // Build up your data
    List rootChildren = new ArrayList();
    rootChildren.add( new MyNode("aa") );
   
    List bbChildren = new ArrayList();
    bbChildren.add( new MyNode("bb.1") );
    bbChildren.add( new MyNode("bb.2") );
    bbChildren.add( new MyNode("bb.3") );
    rootChildren.add( new MyNode("bb", bbChildren) );
   
    rootChildren.add( new MyNode("cc") );
   
    MyNode rootNode = new MyNode("root", rootChildren);
   
    fileTree = new JTree(new FileSystemModel(new MyTreeNode(rootNode)));
    getContentPane().add(fileTree);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(640, 480);
    setVisible(true);
  }
 
 
 
  public static void main(String args[]) {
    new FileTreeFrame("");
  }
}

File MyNode.java
============
import java.util.List;

public class MyNode {
      
      private String name;
      private List children;
      
      public MyNode(String name) {
            this.name = name;
      }
      public MyNode(String name, List children) {
            this.name = name;
            this.children = children;
      }

      public boolean hasChildren() {
            return children!=null && children.size()>0;
      }
      
      public String toString() {
            return name;
      }
      
      public List getChildren() {
            return children;
      }
}

File MyTreeNode.java
===============
import java.util.Iterator;

import javax.swing.tree.DefaultMutableTreeNode;

public class MyTreeNode extends DefaultMutableTreeNode {

    public MyTreeNode(MyNode node) {
        super(node);
        addSubNodes();
    }

    private void addSubNodes() {
          MyNode content = (MyNode)getUserObject();
          if (content!=null && content.hasChildren()) {
                for (Iterator it = content.getChildren().iterator(); it.hasNext();) {
                      add( new MyTreeNode((MyNode)it.next()) );
                }
          }
    }
   
   
}

File FileSystemModel.java
==================
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

class FileSystemModel extends DefaultTreeModel {
      
        public FileSystemModel(DefaultMutableTreeNode node) {
              super(node);
        }
        
        public boolean isLeaf(Object node) {
              MyTreeNode treeNode = (MyTreeNode)node;
              return !((MyNode)treeNode.getUserObject()).hasChildren();
        }
}
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22669241
Remark: I worked with List's instead of Vector's.  (but that's no big deal since Vector implements the List interface)
0
 

Author Comment

by:Sreejith22
ID: 22675788
ZZYNX,

Thanks for the valuable help and the code(it was really a piece of cake).

Now regarding the implementation

1) There is no concept of a root directory or folder. So I added the line of code "fileTree.setRootVisible(false);" . But the directory now opens only on double click.

2) I will make the working concept crystal clear.


FIRST LEVEL
=============
I get all the file and folder names inside a 'single vector' from the database.

Initially I do not know whether the names in this vector are associated with a file or a folder. I do the checking of this with a method which returns true if the name is associated with a folder and false if it is a file.

Based on whether the name is a file or folder, I give the file/folder icon against that name.

With this my first level of implementation is over.



SECOND LEVEL
=============
The second level implementation is solely associated with opening of folders which I obtained in the first level.

When I click on the node of a directory, the contents of this particular directory is obtained from the database in a vector(folder and file names as in the first level).

Next I use the points mentioned in FIRST LEVEL for displaying the contents of this particular directory  by expanding it.


I am totally stuck with the implementation of jtree mentioned above and I hope you understand the state of difficulty I face.
Please say if I am not clear with any of the points mentioned above.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22676327
>> But the directory now opens only on double click.
If you refer to the "bb" node, that was also with a root node.
If you want to expand all nodes by default have a look a this example code:
Expanding or Collapsing All Nodes in a JTree Component: http://www.exampledepot.com/egs/javax.swing.tree/ExpandAll.html
(But I don't think you want this since you say:
>> When I click on the node of a directory, the contents of this particular directory is obtained from the database in a vector(folder and file names as in the first level).
I guess you mean double-click

>>Based on whether the name is a file or folder, I give the file/folder icon against that name.
That's what I do in the method: FileSystemModel.isLeaf() in combination with MyNode.hasChildren()
In your case hasChildren() should return the result of isDirectory() [= a method which returns true if the name is associated with a folder and false if it is a file.]

>> When I click on the node of a directory, the contents of this particular directory is obtained from the database in a vector(folder and file names as in the first level).
That means you have to postpone the execution of MyTreeNode.addSubNodes() until one double-clicks on a node
0
 

Author Comment

by:Sreejith22
ID: 22676531
>>I guess you mean double-click
I wish to expand a directory by pressing '+' on its side. If that is not at all possible with the current scenario, I have no other option except double click( I referred to '+' by saying 'node')

>>That means you have to postpone the execution of MyTreeNode.addSubNodes() until one double-clicks(or expands using '+') on a node

So I should avoid this pattern 'rootChildren.add( new MyNode("bb", bbChildren) );' and implement something different rt?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22676586
>> I wish to expand a directory by pressing '+' on its side.
By default you expand a JTree node by
* clickin on the '+'
OR
* double-clicking the node

You listen to that event by doing this:

fileTree.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() {
            public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) {
                onTreeCollapsed(evt);
            }
            public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {
                onTreeTreeExpanded(evt);
            }
});

with

private void onTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {
     if (!evt.getSource().equals(fileTree))
         return;
     MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent()); // << currently selected node ==  node expanded
     ...
}

>> So I should avoid this pattern 'rootChildren.add( new MyNode("bb", bbChildren) );' and implement something different rt?
Indeed. Initially the only thing you know is that "bb" is a directory. And because of that isLeaf() will return false and because of that a '+' will be available before the node.
When you click that '+' you trigger the onTreeExpanded() method where you should query for the children of that directory and add them to the tree node
0
 

Author Comment

by:Sreejith22
ID: 22676625
>>;MyNode rootNode = new MyNode("root", rootChildren);

In that I did not want that "root", and for that I added "fileTree.setRootVisible(false);"

Once I added that line, no '+' is shown next to 'bb'. How to get around this?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22676676
>> Once I added that line, no '+' is shown next to 'bb'. How to get around this?
By adding the line

  fileTree.setShowsRootHandles(true);
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22676686
0
 

Author Comment

by:Sreejith22
ID: 22676759
>>Thanks for that valuable link. It was quite informative and worth reading.
0
 

Author Comment

by:Sreejith22
ID: 22676764
Is there any method to show the directories first and files last as I showed in the structure in my first post?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22677144
>> Is there any method to show the directories first and files last as I showed in the structure in my first post?
No. The order of the nodes is simply determined by the order you add them to their parent.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22677150
>> The order of the nodes is simply determined by the order you add them to their parent.
Well, given that knowledge, the answer is yes: make sure to first add the directory nodes and afterwards the file nodes
0
 

Author Comment

by:Sreejith22
ID: 22684687
>>make sure to first add the directory nodes and afterwards the file nodes
Ok.. I got it
0
 

Author Comment

by:Sreejith22
ID: 22685485
Hi,
I got the first level implementation almost OK.
But I am doubtful about the procedure I used to get a directory icon for a folder name.
ie; I used "rootChildren.add( new MyNode(dirEntry.filename, folderChildren) );" for a directory name, so that I get a directory icon corresponding to it. "folderChildren" is a dummy I used temporarily.
I have attached a screenshot of my output in  http://docs.google.com/Doc?id=dh67rfq_0f4h8dw46
Kindly check.
I do not know whether this is the correct approach to get a directory icon.

If this is the correct approach
* How will I remove the dummy leaves ("This will be the child leaf.") and load that directory with the names which I obtain inside "private void onTreeExpanded" when I expand the node.

If this is not the correct approach
* What is the alternative?
			//FIRST LEVEL IMPLEMENTATION

			Vector rootChildren = new Vector();

			folderChildren.add( new MyNode("This will be the child leaf.") );

			

			for(Enumeration e = vectRes1.elements(); e.hasMoreElements();)

			{

				Object o = e.nextElement();

				final SFTPv3DirectoryEntry dirEntry = (SFTPv3DirectoryEntry)o;

				if(!(dirEntry.attributes.isDirectory())){

					 rootChildren.add( new MyNode(dirEntry.filename) );

				}

				else

				{

					rootChildren.add( new MyNode(dirEntry.filename, folderChildren) );

					

				}

			}

		   

		    MyNode rootNode = new MyNode("root", rootChildren);

		    fileTree = new JTree(new FileSystemModel(new MyTreeNode(rootNode)));

		    fileTree.setRootVisible(false);

Open in new window

0
 
LVL 37

Expert Comment

by:zzynx
ID: 22685712
>> If this is not the correct approach
>> * What is the alternative?
To make the JTree display a "+" in front of a node *the only thing* to do is make sure that for that node FileSystemModel.isLeaf() returns false.
It is really that simple!

If one clicks on that "+" (or double-clicks) then you can check if there are children to add.
If there are no children to add, the "+" disappears, if there are the "+" becomes "-".
0
 

Author Comment

by:Sreejith22
ID: 22700875
>>To make the JTree display a "+" in front of a node *the only thing* to do is make sure that for that node FileSystemModel.isLeaf() returns false.

I did that using "rootChildren.add( new MyNode(dirEntry.filename, folderChildren) );"  , so that isleaf returns false for directories.That is the only option I have I guess. I followed the approach given in your code and I hope that it is the correct method.

But once I click that '+', literally I do not know how to reload  that particular parent directory with  the children which I have inside the vector- folderChildren.
I know that I have to do all these stuffs inside treeExpanded, but How I does is the real question.
Please help.
0
 

Author Comment

by:Sreejith22
ID: 22700917
If I need to post doubts related to this thread as a new topic , please say that. I will close this and assign points and start a fresh topic and needless to say, zzynx, you deserve more than 1000.

Please do provide soln. to my above posted doubt.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22700953
>> That is the only option I have I guess.
I don't think so.
I thought on this:

public boolean isLeaf(Object node) {
    MyTreeNode treeNode = (MyTreeNode)node;
    return ??? .... isDirectory();
}

I don't know exactly how to go from the available MyTreeNode to the object on which you can call isDirectory(), but I guess you will.

>> If I need to post doubts related to this thread as a new topic , please say that.
For the moment I still consider all your subquestions as belonging to the same question/problem.
0
 

Author Comment

by:Sreejith22
ID: 22701346
>>But once I click that '+', literally I do not know how to reload  that particular parent directory with  the children(I obtain the children inside a vector by passing the parent name).
I know that I have to do all these stuffs inside treeExpanded, but How I does is the real question.

You have aleady seen http://docs.google.com/View?docid=dh67rfq_0f4h8dw46. In that how will I replace "This will be the child leaf", with the names of children I have inside the vector?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22701598
if you don't rely on the content of rootChildren to decide whether it is a leaf or not, you don't have to prefill that rootChildren with that dummy node
>> folderChildren.add( new MyNode("This will be the child leaf.") );
and then you don't have to replace that "This will be the child leaf", with the real names of children.

What I mean is this:

>>FIRST LEVEL
>>=========
>> I get all the file and folder names inside a 'single vector' from the database.
That's OK.

>> Initially I do not know whether the names in this vector are associated with a file or a folder.
That's OK.
>> I do the checking of this with a method which returns true if the name is associated with a folder and false if it is a file.
isDirectory() I guess. That's OK.
Use that method in isLeaf() to return false or true (and **don't** look at the contents of rootChildren)

>> SECOND LEVEL
>> =============
>> The second level implementation is solely associated with opening of folders which I obtained in the first level.
That's OK.

>> When I click on the node of a directory,
then onTreeExpanded() will be triggered and that's the time you have to
* query for the contents of the particular directory from the database
* add the subnodes to the current node based on these results

private void onTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {
     if (!evt.getSource().equals(fileTree))
         return;
     MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent()); // << currently selected node ==  node expanded
     MyNode myNode = (MyNode) node.getUserObject();
     String nameOfDirectory = myNode.getName();  // You have to add this one to the class MyNode
     
     // Query the database for the files & directories contained in 'nameOfDirectory'
     // for each of them do something like
     YourFileSystemModel.insertNodeInto( new MyTreeNode( new MyNode(nameOfDirectory) ) ), node, 0);
}
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 37

Expert Comment

by:zzynx
ID: 22701745
To give you a better idea of what I mean, here's some adapted code:

File FileTreeFrame.java
================
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JTree;
public class FileTreeFrame extends JFrame {
  private JTree fileTree;
 
  private FileSystemModel fileSystemModel;
 
 
  public FileTreeFrame(String abc) {
    super("JTree FileSystem Viewer");
   
    // Build up your data
    List rootChildren = new ArrayList();
    rootChildren.add( new MyNode("aa") );
    rootChildren.add( new MyNode("bb") );
    rootChildren.add( new MyNode("cc") );
   
    MyNode rootNode = new MyNode("root", rootChildren);
   
    fileSystemModel = new FileSystemModel(new MyTreeNode(rootNode));
    fileTree = new JTree(fileSystemModel);
    fileTree.setRootVisible(false);
    fileTree.setShowsRootHandles(true);
    fileTree.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() {
          public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) {
                // Not yet implemented
          }
          public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {
            onTreeExpanded(evt);
        }
    });
    getContentPane().add(fileTree);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(640, 480);
    setVisible(true);
  }
 
  private void onTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {
     if (!evt.getSource().equals(fileTree))
         return;
     MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent());
       MyNode myNode = (MyNode)node.getUserObject();
       if (myNode.getName().equals("bb")) {
             fileSystemModel.insertNodeInto(new MyTreeNode( new MyNode("bb.1") ), node, 0);
             fileSystemModel.insertNodeInto(new MyTreeNode( new MyNode("bb.2") ), node, 1);
             fileSystemModel.insertNodeInto(new MyTreeNode( new MyNode("bb.3") ), node, 2);
       }
  }  
 
  public static void main(String args[]) {
    new FileTreeFrame("");
  }
}

File FileSystemModel.java
==================
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

class FileSystemModel extends DefaultTreeModel {
      
        public FileSystemModel(DefaultMutableTreeNode node) {
              super(node);
        }
        
        public boolean isLeaf(Object node) {
              MyTreeNode treeNode = (MyTreeNode)node;
              MyNode myNode = (MyNode)treeNode.getUserObject();
              if (myNode.getName().equals("root"))
                    return false; // root is never a leaf
              else
                    return !myNode.getName().equals("bb");
        }
}

* MyTreeNode.java isn't changed
* In the file MyNode.java I added one new method:

      public String getName() {
            return name;
      }
0
 

Author Comment

by:Sreejith22
ID: 22701865
>>insertNodeInto( new MyTreeNode( new MyNode(nameOfDirectory) ) ), node, 0);


Here nameOfDirectory means , the name of file/folders which we get from the database for that particular parent directory rt?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22701942
Have a look @ the updated code I just posted
0
 

Author Comment

by:Sreejith22
ID: 22709718
One problem I face now.

1) I use the same vector which I use in the first level implementation, to load the child names. I use this same vector for the reason that, I am under the assumption that , after the first level implementation(by taking the names from the vector), the vector remains idle and is of no use till the end. So I planned to load the children of individual directories, while opening the directory, inside this vector itself.

2) Now, my problem ----- When I do step 1 mentioned above, ie; when I load the children of a particular directory, inside that vector which I used for first level implementation, and when I try to open the directory, each and everything is shown as leaves

Creating individual vectors for individual directories is not the correct approach I guess.

How can I get around this problem?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22710877
>> each and everything is shown as leaves
That means there's something incorrect in the isLeaf() method

>> How can I get around this problem?
You'll have to show me your code, I'm afraid
0
 

Author Comment

by:Sreejith22
ID: 22718163
ZZYNX,
I have attached the code here. Hope you will understand what I have done here. If Iyou have any doubts with any particular line of code, kindly ask.
I have also uploaded the screenshot of my output. Please have a look at http://docs.google.com/Doc?id=dfzrknk_18dhbjx3g4 so that things will be crystal clear.



/**File FileTreeFrame.java

================*/

import java.awt.Dimension;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.util.Collections;

import java.util.Comparator;

import java.util.Enumeration;

import java.util.Vector;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;

import javax.swing.tree.TreePath;

import com.lynxoft.dld.dev.DownloadAdapter;

import com.trilead.ssh2.Connection;

import com.trilead.ssh2.SFTPv3Client;

import com.trilead.ssh2.SFTPv3DirectoryEntry;
 
 

public class myTree extends JFrame {
 

private JTree fileTree;

private	SFTPv3Client sftp;

public DownloadAdapter downloadAdapter;

Connection connexion;

myApp frameParent = null;

private	static String currRep = "/"; 

int compteurFileChooser = 0;

private	Object[][] donnees;

public Vector vectRes;

public static Vector vectRes1;

int tri = 31;

Vector folderChildren = new Vector();

static Vector rootChildren = new Vector();

  private FileSystemModel fileSystemModel;

 

  public myTree(SFTPv3Client sftp, Connection conn, DownloadAdapter downloadAdapt,myApp frameP) {

   

	    this.sftp = sftp;

		this.downloadAdapter = downloadAdapt;

		this.connexion = conn;

		this.frameParent = frameP;

	  

    init(this.currRep,this.sftp);

    

  }

 
 

  

  public void init(String rep, final SFTPv3Client sftp){
 

		this.compteurFileChooser = 0;

		this.donnees	= null;

		this.vectRes	= null;

		this.vectRes1	= null;

		this.sftp 		= sftp;

		this.currRep	= rep;

			

		getContents();

			

			//FIRST LEVEL IMPLEMENTATION

			

			

			for(Enumeration e = vectRes1.elements(); e.hasMoreElements();)

			{

				Object o = e.nextElement();

				final SFTPv3DirectoryEntry dirEntry = (SFTPv3DirectoryEntry)o;

					rootChildren.add( new MyNode(dirEntry.filename) );

					

			}

			

		    MyNode rootNode = new MyNode("root_untouched", rootChildren);

		    final FileSystemModel model = new FileSystemModel(new MyTreeNode(rootNode));

		    fileTree = new JTree(model);

		    fileTree.setRootVisible(false);

		    fileTree.setShowsRootHandles(true);

		    

		    

		    

		    

		    

		    

		    fileTree.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() {

		        public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) {

		            //treeCollapsed(evt);

		        }

		        public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {

		        	

		        	 if (!evt.getSource().equals(fileTree))

		                 return;

		        	 MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent());

		        	 MyNode myNode = (MyNode) node.getUserObject();

		             String nameOfDirectory = myNode.getName();  // You have to add this one to the class MyNode

		             System.out.println("Namof parent directory"+nameOfDirectory);

		             nameOfDirectory.replace("root_untouched", "");

		             currRep = nameOfDirectory; // Now I change the path(currRep) which will be used for getting contents of child in getContents();

		             getContents();////Here I get children corresponding to the parent inside vectRes1 which was used in the first level

		             for(Enumeration e = vectRes1.elements(); e.hasMoreElements();)

			 			{

			 				Object o = e.nextElement();

			 				final SFTPv3DirectoryEntry dirEntry = (SFTPv3DirectoryEntry)o;

			 				System.out.println("child:"+dirEntry.filename);

			 				model.insertNodeInto( new MyTreeNode( new MyNode(dirEntry.filename) ) , node, 0);

			 			}

		             

		        }

		});

			

			

		    fileTree.addMouseListener(new MouseAdapter()

		    {

		    	public void mouseClicked(MouseEvent e)

		    	{

		    		TreePath treePath = fileTree.getPathForLocation(e.getX(), e.getY());

		    		fileTree.setSelectionPath(treePath);

		    		fileTree.scrollPathToVisible(treePath);

		    	}

		    });
 

	

	}

  // Method which is used to get the contents. Here contents will be added to vectRes1. "currRep" is the path we give.

  public void getContents(){

	  try{

			this.vectRes = this.sftp.ls(currRep);

		}

		catch (Exception e) {

		}

		

		int iCpt = 0;

		this.vectRes1 = new Vector();

		for(Enumeration e = vectRes.elements(); e.hasMoreElements();)

		{

			Object o = e.nextElement();

			SFTPv3DirectoryEntry dirEntry1 = (SFTPv3DirectoryEntry)o;

			if(!dirEntry1.filename.matches("^[.]{1}[a-zA-Z0-9]+")

					&& !dirEntry1.filename.equals(".")

					&& !dirEntry1.filename.equals("..")

					&& !dirEntry1.filename.startsWith("."))

			{

				vectRes1.add(dirEntry1);

			}

				

		}

		Collections.sort((Vector)vectRes1, new Comparator(){

			public int compare(Object arg0, Object arg1) {

				int test=0;

				int testDirArg0 = 0;

				int testDirArg1 = 0;

				if(((SFTPv3DirectoryEntry)arg0).attributes.isDirectory()) testDirArg0 = 1;

				else testDirArg0 = 2;

				if(((SFTPv3DirectoryEntry)arg1).attributes.isDirectory()) testDirArg1 = 1;

				else testDirArg1 = 2;

				

				if(tri==21) test = ((SFTPv3DirectoryEntry)arg0).filename.compareToIgnoreCase(((SFTPv3DirectoryEntry)arg1).filename);

				if(tri==22) test = ((SFTPv3DirectoryEntry)arg1).filename.compareToIgnoreCase(((SFTPv3DirectoryEntry)arg0).filename);

				if(tri==31) test = getExtension(((SFTPv3DirectoryEntry)arg0).filename).compareToIgnoreCase(getExtension(((SFTPv3DirectoryEntry)arg1).filename));

				if(tri==32) test = getExtension(((SFTPv3DirectoryEntry)arg1).filename).compareToIgnoreCase(getExtension(((SFTPv3DirectoryEntry)arg0).filename));

				if(tri==41) test = (int) (((SFTPv3DirectoryEntry)arg0).attributes.size - ((SFTPv3DirectoryEntry)arg1).attributes.size);

				if(tri==42) test = (int) (((SFTPv3DirectoryEntry)arg1).attributes.size - ((SFTPv3DirectoryEntry)arg0).attributes.size);

				if(tri==51) test = (int) (((SFTPv3DirectoryEntry)arg0).attributes.mtime - ((SFTPv3DirectoryEntry)arg1).attributes.mtime);

				if(tri==52) test = (int) (((SFTPv3DirectoryEntry)arg1).attributes.mtime - ((SFTPv3DirectoryEntry)arg0).attributes.mtime);

				

								

				

				return test;

			}

		});

		

  }

  // This method is not of much importance.

  public String getExtension(String name)

	{

		if(name.lastIndexOf(".")!=-1)

		{

			String extensionPossible = name.substring(name.lastIndexOf(".")+1, name.length());

			if(extensionPossible.length()>6)

			{

				return "";

			}

			else 

			{

				return extensionPossible;

			}

		}

		else return "";

	}

  

  

  public JScrollPane getPane(){

	     JScrollPane pane = new JScrollPane(fileTree);

	     pane.setPreferredSize(new Dimension(320, 200));

	     return pane;

  }

  

}

class FileSystemModel extends DefaultTreeModel {

    

    public FileSystemModel(DefaultMutableTreeNode node) {

          super(node);

    }

    

    public boolean isLeaf(Object node) {

    	boolean isLeaf = true;

    	

    	MyTreeNode treeNode = (MyTreeNode)node;

          

    	  MyNode myNode = (MyNode)treeNode.getUserObject(); 

          if (myNode.getName().equals("root_untouched"))

              return false; // root is never a leaf

        else

              return !(isDir(myNode.getName()));

          

          

          

    }

    // Method to check whether the given name corresponds to a directory

    public synchronized boolean isDir(String nom)

	{

		boolean result = false;

		for(Enumeration e = myTree.vectRes1.elements(); e.hasMoreElements();)

		{

			Object o = e.nextElement();

			if(((SFTPv3DirectoryEntry)o).filename.equals(nom)) 

			{

				if(((SFTPv3DirectoryEntry)o).attributes.isDirectory()) result = true;

				

			}

		}

		return result;

	}

}

Open in new window

0
 
LVL 37

Expert Comment

by:zzynx
ID: 22718882
I see.
The reason why you loose the directory icon for 'kklop', 'Fer', 'Synopsis",... and so on when you "open" the directory 'Backup' is clear to me:
your method isDir() in FileSystemModel uses 'vectRes1' to decide if a node is a directory or a file and since that one changed...

Don't think that isLeaf() is only called once when you add the node to the tree.
It is called whenever a node is repainted (and that's quite a lot of times).
So, your isLeaf() method must
(1) for *EVERY* node
(2) always - at every possible moment -
be able to tell if a node is a leaf node or not.
So your FileSystemModel must really have available the "knowledge" of all nodes currently in the tree.
Since now you use the "vectRes1" variable for that, that is NOT the case.
So what you need inside FileSystemModel is really what I told you in the beginning: for each node 1) its name 2) its children

First level:
node                  name          children?
===============================================
root node                     known        known (all the following)
  kklop                    known         unknown yet
  Fer                          known         unknown yet
  Backup                    known         unknown yet
  ...                          known         unknown yet

  hw.doc                    known         known:none
  Booodrive.rar            known         known:none
  src.rar                    known         known:none

Second level (once e.g. Backup is expanded):

node                  name          children?
==============================================
root node                     known        known (all the following)
  kklop                    known         unknown yet
  Fer                          known         unknown yet
  Backup                    known         unknown yet
   Booodrive.zip      known         known:none
   ...                          known         known:none

   mnb                  known         unknown yet
  ...                          known         unknown yet

  hw.doc                    known         known:none
  Booodrive.rar            known         known:none
  src.rar                    known         known:none

So to make your isLeaf() method work as expected (=make your tree look as expected),
each time a node is expanded you should *extend* (not overwrite) that hierarchical vector with the new information (=the children of the expanded node)

I hope I'm clear enough.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22719141
In fact, I think you don't need that Vector "vectRes1".
The knowledge of the content has to be in your MyNode objects.

Change the class MyNode as follows:

public class MyNode {
     
      private String name;
      private boolean isDirectory;
      private Vector children = new Vector(); // contains the MyNode objects corresponding with the children
      private boolean childrenConstructed = false;
     
      public MyNode(String name, boolean dir) {
            this.name = name;
            this.isDirectory = dir;
      }
      public MyNode(String name, List children) {
            this.name = name;
            this.children = children;
      }

      public boolean isDirectory() {
            return isDirectory;
      }
     
      public String toString() {
            return getName();
      }

      public String getName() {
           return name;
      }
     
      public List getChildren() {
            return children;
      }

      public void constructChildren() {
          if (childrenConstructed) // to avoid you build up the children twice
             return;

          // here you have to write code to fill up the 'children' vector with the correct MyNode objects
          // corresponding with this node's children
          // Kind of your previous getContents() method
          ...
          childrenConstructed = true;
      }
}

Then your isLeaf() method becomes very simple:

    public boolean isLeaf(Object node) {
          MyTreeNode treeNode = (MyTreeNode)node;
        MyNode myNode = (MyNode)treeNode.getUserObject();
        return !myNode.isDirectory();
    }

Your MyTreeNode becomes:

public class MyTreeNode extends DefaultMutableTreeNode {

    private boolean subNodesAdded = false;

    public MyTreeNode(MyNode node) {
        super(node);
        // don't add the subnodes here yet!!!
    }

    public void addSubNodes() {
        MyNode content = (MyNode)getUserObject();
        if (content!=null && content.isDirectory()) {
           content.constructChildren();
           for(Enumeration e = myNode.getChildren(); e.hasMoreElements();) {
              final MyNode entry = (MyNode)e.nextElement();
              add( new MyTreeNode(entry) );
           }
        }
        subNodesAdded = true;
    }

    public boolean areSubNodesAdded() {
        return subNodesAdded;
    }
}

Then your treeExpanded() method becomes:

public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {
                          
   if (!evt.getSource().equals(fileTree))
     return;
   MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent());
   MyNode myNode = (MyNode) node.getUserObject();
   if (!myNode.isDirectory())
      return;
   if (!node.areSubNodesAdded()) {
      node.addSubNodes();
      ((FileSystemModel)fileTree.getModel()).nodeStructureChanged(node); // Needed to visually update the tree
   }
}

Now, if I represent a MyNode object by:  {"<the Name>", <isDirectory()>, [<the children>]}

then @ the first level the MyNode object corresponding with the root could look like this:
[ {"root_untouched", true, [ {"kklop", true, []}, {"Fer", true, []}, {"Backup", true, []}, ... {"hw.doc", false, []}, {"Booodrive.rar", false, []}, {"src.rar", false, []} ]} ]

After having expanded "Backup" it looks like:
[ {"root_untouched", true, [ {"kklop", true, []}, {"Fer", true, []}, {"Backup", true, [ {"Booodrive.zip", false, []}, ..., {"mnb", true, []} ]}, ... {"hw.doc", false, []}, {"Booodrive.rar", false, []}, {"src.rar", false, []} ]} ]

Now, it's up to you to write the code for MyNode.constructChildren() (which is basically your current getContents() method)
I guess it's something like (without any sorting of the children) :

      public void constructChildren() {
          if (childrenConstructed) // to avoid you build up the children twice
             return;

          try {
          Vector res = this.sftp.ls(getName());
          for(Enumeration e = res.elements(); e.hasMoreElements();) {
            SFTPv3DirectoryEntry dirEntry1 = (SFTPv3DirectoryEntry)e.nextElement();
              if(!dirEntry1.filename.matches("^[.]{1}[a-zA-Z0-9]+")
             && !dirEntry1.filename.equals(".")
             && !dirEntry1.filename.equals("..")
             && !dirEntry1.filename.startsWith(".")) {
                   children.add( MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );
            }
          } catch (Exception e) {
             // Think what behaviour you want in this case!!!!
          }
          childrenConstructed = true;
      }

0
 

Author Comment

by:Sreejith22
ID: 22719185
Thanks for the information ZZYNX.
I changed my logic as per your suggestions. It worked almost to perfection-- 95% I should say.

I have 2 problems now.

1) MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent());
     MyNode myNode = (MyNode) node.getUserObject();
       String nameOfDirectory = myNode.getName();  // You have to add this one to the class MyNode
             System.out.println("Name of parent directory"+nameOfDirectory);
Name of directory I get here is incorrect. I get the name of current directory only, ie; if directory B is inside directory A, the path should be A\B - instead , I get only B.

2) Once I expand a node and then I collapse, and after that each time I open, the same contents are added to that directory each time I open it.

Please help with these issues.
0
 

Author Comment

by:Sreejith22
ID: 22719212
ZZYNX, I did not see your post >>In fact, I think you don't need that Vector "vectRes1".

My previous queries correspond to your first post for me today.

0
 
LVL 37

Expert Comment

by:zzynx
ID: 22719234
>> It worked almost to perfection-- 95% I should say.
Good to hear!

>> Name of directory I get here is incorrect.
Well, it's not incorrect. It is something else than you would like ;°)

>> I get the name of current directory only, ie; if directory B is inside directory A, the path should be A\B - instead , I get only B.
Currently you only store the name of the directory, not the path name.
If you would like that, you should store the path name too inside MyNode.

>> 2) Once I expand a node and then I collapse, and after that each time I open, the same contents are added to that directory each time I open it.
I know. That's why in my last post I added the boolean 'subNodesAdded' in MyTreeNode
0
 

Author Comment

by:Sreejith22
ID: 22719300
Ok zzynx,
I am trying with your second post for me today..If I have any problems with that I will ask. I believe that it will work and needless to say, wonderful logic..
"There is no better teacher than our experience and I hope(wish) once I would be able to do as you does the coding ZZYNX"..
Whole hearted thx for the help upto this point ..
Let me proceed with the development.. i will return if i have any doubts or else, I will be back with points
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22719357
>> Whole hearted thx for the help upto this point ..
You're welcome.

>> Let me proceed with the development..
Success

>> i will return if i have any doubts
Sure

>> or else, I will be back with points
:o))
0
 

Author Comment

by:Sreejith22
ID: 22729049
zzynx I am not able to follow the control flow of the program . I am sure that the logic will work, but how it works puzzles me.

1) What is the status of myTree class?

Does this code for first level implementation need to be present anymore in myTree init?
>>for(Enumeration e = temp.elements(); e.hasMoreElements();)
                  {
                        Object o = e.nextElement();
                        final SFTPv3DirectoryEntry dirEntry = (SFTPv3DirectoryEntry)o;
                              rootChildren.add( new MyNode(dirEntry.filename) );
                              
                  }
                  
                MyNode rootNode = new MyNode("root_untouched", rootChildren);
                final FileSystemModel model = new FileSystemModel(new MyTreeNode(rootNode));
                fileTree = new JTree(model);


2)>>children.add( MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );

In this were you trying to add an object? Error suggestion is shown that method  MyNode(String,boolean) does not exist.(I see a similar constructor there)

3)What is the status of the public void getContents() method which I call in the init method of myTree class. Does getContents() need to be present any further in myTree? Also, kindly say what are the vital changes I need to do in myTree's init method?

4) From the init method of myTree onwards, can you please say how the program flow goes?

Please help with these doubts..
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22730271
First of all

* Your question 2):
>> Error suggestion is shown that method  MyNode(String,boolean) does not exist.
I told you:

>>Change the class MyNode as follows:

>>public class MyNode {
     
>>      private String name;
>>      private boolean isDirectory;
>>      private Vector children = new Vector(); // contains the MyNode objects corresponding with the children
>>      private boolean childrenConstructed = false;
     
>>      public MyNode(String name, boolean dir) {                  // <<<<<<<<< this is the one
>>            this.name = name;
>>            this.isDirectory = dir;
>>      }

* Your question 1)
>> Does this code for first level implementation need to be present anymore in myTree init?
No.

I think this should work:

  public FileTreeFrame(String abc) {
    super("JTree FileSystem Viewer");
   
    MyNode root = new MyNode("root_untouched", true);
    MyTreeNode rootNode = new MyTreeNode(root);
    fileSystemModel = new FileSystemModel(rootNode);
    fileTree = new JTree(fileSystemModel);
    fileTree.setRootVisible(false);
    fileTree.setShowsRootHandles(true);
    rootNode.addSubnodes(); // <<<<<<<<<< programatically expand the root node

Your question 3)
>> Does getContents() need to be present any further in myTree?
No. It's functionality is replaced by constructChildren() [but you still need to add the sorting of the subnodes in constructChildren()]

>> 4) From the init method of myTree onwards, can you please say how the program flow goes?
Well, there's not much to say about.
1) You initialize the tree with the root node,
2) you add the subnodes to that rootnode
and from then on
3) every double-click on a directory node triggers the addSubNodes() method of that node which ensures that the model then also contains the sub node information.
0
 

Author Comment

by:Sreejith22
ID: 22737967
1)
>>Change the class MyNode as follows:
I have changed that earlier itself. The point I was trying to say was that, in your suggestion, "children.add( MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );" , it was trying to call a constructor, from inside the add method of a vector. I know that what you try to say is add a child name and whether it is a directory/file to the children vector(boolean). It means adding 2 objects to a vector at the same time.
Kindly clarify this point.

2) I have changed the for loop condition in the addSubNodes() method of MyTreeNode as follows

MyNode content = (MyNode)getUserObject();
        if (content!=null && content.isDirectory()) {
           content.constructChildren();
           for(Enumeration e = content.getChildren().elements(); e.hasMoreElements();) // I changed the condition here. I used the  object 'content' itself instead of creating another MyNode object. Please say if there is anything wrong in this.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22738337
>> children.add( MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );
Sorry. That's a typo.
That should have been

       children.add( new MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );

of course.

>> It means adding 2 objects to a vector at the same time
No, it's adding one (MyNode) object of which you specify two attributes: its name and a boolean indicating if it's a directory or not


>> I have changed the for loop condition in the addSubNodes() method of MyTreeNode as follows
That's another typo.
Your correction is like I meant it to be indeed.
0
 

Author Comment

by:Sreejith22
ID: 22747746
zzynx,
I am not getting proper output. In the first level implementation , the code works upto the method "constructChildren" and I have sorted and added to the vector as you suggsted --  
>>children.add( new MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );

To my unluck, something, somewhere is going wrong and I cant see the output after I add Jtree to the scrollpane. At last I made the root directory visible just to see anything happens, and root directory alone is displayed. I kept debugging and debugging for hours, but could not find the reason.
I am posting my code here. If you get any idea as to what  the problem can be,  please help.
/**File FileTreeFrame.java

================*/

import java.awt.Dimension;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTree;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;

import javax.swing.tree.TreePath;

import com.trilead.ssh2.Connection;

import com.trilead.ssh2.SFTPv3Client;

public class myTree extends JFrame {

private JTree fileTree;

private	SFTPv3Client sftp;

Connection connexion;

int compteurFileChooser = 0;

private FileSystemModel fileSystemModel;

 

  public void init(final SFTPv3Client sftp){
 

		this.compteurFileChooser = 0;

		this.sftp 		= sftp;

		System.out.println("chaaaaaaaaaaaaaaanged");

		    

			  	MyNode root = new MyNode("root_untouched", true);

			  	root.setSftp(this.sftp);

			    MyTreeNode rootNode = new MyTreeNode(root);

			    

			    fileSystemModel = new FileSystemModel(rootNode);

			    fileTree = new JTree(fileSystemModel);

			    //fileTree.setRootVisible(false);

			    fileTree.setShowsRootHandles(true);

			    System.out.println("deeeeeeeeebug1");

			    rootNode.addSubNodes(); // <<<<<<<<<< programatically expand the root node

		    

		    

		    

		    

		    fileTree.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() {

		        public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) {

		            //treeCollapsed(evt);

		        }

		        public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {

                    

		        	   if (!evt.getSource().equals(fileTree))

		        	     return;

		        	   MyTreeNode node = (MyTreeNode)(evt.getPath().getLastPathComponent());

		        	   

		        	   MyNode myNode = (MyNode) node.getUserObject();

		        	   if (!myNode.isDirectory())

		        	      return;

		        	   if (!node.areSubNodesAdded()) {

		        	      node.addSubNodes();

		        	      ((FileSystemModel)fileTree.getModel()).nodeStructureChanged(node); // Needed to visually update the tree

		        	   }

		        	}

		});

			

			

		    fileTree.addMouseListener(new MouseAdapter()

		    {

		    	public void mouseClicked(MouseEvent e)

		    	{

		    		TreePath treePath = fileTree.getPathForLocation(e.getX(), e.getY());

		    		fileTree.setSelectionPath(treePath);

		    		fileTree.scrollPathToVisible(treePath);

		    	}

		    });
 

	

	}

  public JScrollPane getPane(){

	     JScrollPane pane = new JScrollPane(fileTree);

	     pane.setPreferredSize(new Dimension(320, 200));

	     return pane;

  }

  

}

class FileSystemModel extends DefaultTreeModel {

    

    public FileSystemModel(DefaultMutableTreeNode node) {

    	super(node);

    	System.out.println("inside FileSystemModel");

    }

    

    public boolean isLeaf(Object node) {

        MyTreeNode treeNode = (MyTreeNode)node;

      MyNode myNode = (MyNode)treeNode.getUserObject();

      return !myNode.isDirectory();

  }

   

}
 

=======================================================================
 
 

/*File MyTreeNode.java

===============*/

import java.util.Enumeration;
 

import javax.swing.tree.DefaultMutableTreeNode;
 

import com.trilead.ssh2.SFTPv3Client;

public class MyTreeNode extends DefaultMutableTreeNode {
 

    private boolean subNodesAdded = false;
 

    public MyTreeNode(MyNode node) {

    	

        super(node);

        System.out.println("inside MyTreeNode");

        // don't add the subnodes here yet!!!

    }
 

    public void addSubNodes() {

    	 

        MyNode content = (MyNode)getUserObject();

        System.out.println("directory root_untouched"+content.isDirectory());

        System.out.println("directory root_untouched"+content.getName());

        if (content!=null && content.isDirectory()) {

        	System.out.println("deeeeeeeeebug2");

           content.constructChildren();

           for(Enumeration e = content.getChildren().elements(); e.hasMoreElements();) {

              final MyNode entry = (MyNode)e.nextElement();

              add( new MyTreeNode(entry));

           }

           System.out.println("deeeeeeeeebug3");

        }

        subNodesAdded = true;

    }
 

    public boolean areSubNodesAdded() {

        return subNodesAdded;

    }

}
 
 
 

=======================================================================
 

/*File MyNode.java

============*/

import java.util.Collections;

import java.util.Comparator;

import java.util.Enumeration;

import java.util.Vector;
 

import com.trilead.ssh2.SFTPv3Client;

import com.trilead.ssh2.SFTPv3DirectoryEntry;

public class MyNode {

    

    private String name;

    private boolean isDirectory;

    int tri = 31;

    private Vector children = new Vector(); // contains the MyNode objects corresponding with the children

    private boolean childrenConstructed = false;

    static Vector res = new Vector();

    private	SFTPv3Client sftp;

    public MyNode(String name, boolean dir) {

          this.name = name;

          this.isDirectory = dir;

    }

    public MyNode(String name, Vector children) {

          this.name = name;

          this.children = children;

    }
 

    public boolean isDirectory() {

          return isDirectory;

    }

    public void setSftp(SFTPv3Client sftp){

    	this.sftp 		= sftp;

    }

    public String toString() {

          return getName();

    }
 

    public String getName() {

         return name;

    }

   

    public Vector getChildren() {

          return children;

    }
 

    public void constructChildren() {

    	if (childrenConstructed) // to avoid you build up the children twice

            return;

System.out.println("construction @");

Vector temp = new Vector();         

try {

        	 System.out.println("construction *");

        String	 currRep = "/"; 

        

         res = sftp.ls(currRep);

         for(Enumeration e = res.elements(); e.hasMoreElements();) {

           SFTPv3DirectoryEntry dirEntry1 = (SFTPv3DirectoryEntry)e.nextElement();

             if(!dirEntry1.filename.matches("^[.]{1}[a-zA-Z0-9]+")

            && !dirEntry1.filename.equals(".")

            && !dirEntry1.filename.equals("..")

            && !dirEntry1.filename.startsWith(".")) {

            	 System.out.println("for tree, the file name is:"+dirEntry1.filename);

            	 temp.add(dirEntry1); 

            	 

           }}

         } catch (Exception e) {

            // Think what behaviour you want in this case!!!!

         }

         Collections.sort((Vector)temp, new Comparator(){

 			public int compare(Object arg0, Object arg1) {

 				int test=0;

 				int testDirArg0 = 0;

 				int testDirArg1 = 0;

 				if(((SFTPv3DirectoryEntry)arg0).attributes.isDirectory()) testDirArg0 = 1;

 				else testDirArg0 = 2;

 				if(((SFTPv3DirectoryEntry)arg1).attributes.isDirectory()) testDirArg1 = 1;

 				else testDirArg1 = 2;

 				

 				if(tri==21) test = ((SFTPv3DirectoryEntry)arg0).filename.compareToIgnoreCase(((SFTPv3DirectoryEntry)arg1).filename);

 				if(tri==22) test = ((SFTPv3DirectoryEntry)arg1).filename.compareToIgnoreCase(((SFTPv3DirectoryEntry)arg0).filename);

 				if(tri==31) test = getExtension(((SFTPv3DirectoryEntry)arg0).filename).compareToIgnoreCase(getExtension(((SFTPv3DirectoryEntry)arg1).filename));

 				if(tri==32) test = getExtension(((SFTPv3DirectoryEntry)arg1).filename).compareToIgnoreCase(getExtension(((SFTPv3DirectoryEntry)arg0).filename));

 				if(tri==41) test = (int) (((SFTPv3DirectoryEntry)arg0).attributes.size - ((SFTPv3DirectoryEntry)arg1).attributes.size);

 				if(tri==42) test = (int) (((SFTPv3DirectoryEntry)arg1).attributes.size - ((SFTPv3DirectoryEntry)arg0).attributes.size);

 				if(tri==51) test = (int) (((SFTPv3DirectoryEntry)arg0).attributes.mtime - ((SFTPv3DirectoryEntry)arg1).attributes.mtime);

 				if(tri==52) test = (int) (((SFTPv3DirectoryEntry)arg1).attributes.mtime - ((SFTPv3DirectoryEntry)arg0).attributes.mtime);

 				

 				return test;

 			}

 		});

     	

         for(int i=0; i< temp.size(); i++){

	       	 SFTPv3DirectoryEntry dirEntry1 = (SFTPv3DirectoryEntry)temp.elementAt(i);

	       	 System.out.println("important check"+dirEntry1.filename+"  "+dirEntry1.attributes.isDirectory());

        	 children.add( new MyNode(dirEntry1.filename, dirEntry1.attributes.isDirectory()) );

         }

         

        childrenConstructed = true;

    

}

    public String getExtension(String name)

	{

		if(name.lastIndexOf(".")!=-1)

		{

			String extensionPossible = name.substring(name.lastIndexOf(".")+1, name.length());

			if(extensionPossible.length()>6)

			{

				return "";

			}

			else 

			{

				return extensionPossible;

			}

		}

		else return "";

	}   

}

Open in new window

0
 
LVL 37

Expert Comment

by:zzynx
ID: 22774616
>> I kept debugging and debugging for hours, but could not find the reason.
You should follow the program step by step and it should rather quickly become clear where the problem is situated.
Set a break point at the line

              rootNode.addSubNodes(); // <<<<<<<<<< programatically expand the root node

and then step into every method you encounter.
I have no idea.

Just one remark:
I see you have added a method setSftp() to MyNode. But I see you call it for the root node only. Shouldn't you call it for other nodes too?
0
 

Author Comment

by:Sreejith22
ID: 22814940
Zzynx,
Thanks a lot. I did not get the output yet. I tried debugging and kept it pending. Anyway, it would be unfair if I hold back closing this thread until I get my output. Anyway, I am closing this thread and assigning full points and a bunch of thanks for your precious help. If I do not get the output even after my further testings, I will come back with a fresh thread.
Once again,
THANKS ZZYNX.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22821685
You're welcome.
I wish you success.
Thanx 4 axxepting.
0
 

Author Comment

by:Sreejith22
ID: 22992020
zzynx,
I got it successfully implemented.
Can you please say, how can I refresh a particular directory alone.

The purpose is that, I am implementing drag and drop in this jtree. So if I drag an item from my machine into a directory in the JTree or directly to the root tree, I have a function which works and uploads this dragged item to the server.
So I just would like to know, how to refresh that particular directory and show the newly added item in the server.
Please help with a solution.
If needed I will post this as a fresh question.

Regards,
Sreejith
0
 

Author Comment

by:Sreejith22
ID: 22992027
>>how to refresh that particular directory and show the newly added item in the server.

CORRECTION

how to refresh that particular directory and show the newly added item in the server, in my JTree directory.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22992406
Hi Sreejith22,

I think it is best to open a new question for this (with a refering link to this question as background information)
0
 

Author Comment

by:Sreejith22
ID: 23201555
ZZYNX,
Can you kindly refer the question posted in http://www.experts-exchange.com/Programming/Languages/Java/Q-23988250-Jtree-implementation-based-on-structure-given-ZZYNX-objects-CEHJ-and-others-help-needed.html

I need some help badly. Since you have a thorough knowledge about my requirement background(based on this thread), I am sure, you can help me with some valuable tips.
No one will be interested to study the 4 classes from the scratch which I posted in the new thread, but since you have got a crystal clear idea about those 4 classes, I am sure, you can help me in some way. Please..
Warm Regards,
Anees
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now