Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / March 2005

Tip: Looking for answers? Try searching our database.

killing branches on a JTree

Thread view: 
Ike - 15 Mar 2005 16:54 GMT
Ive been wrestling for nearly a day with what ought to be a simple
algorithm. I'm trying to find leafs on a JTree where the data emanates from
a given file (which has an integer index), whereby I delete the leaf itself,
and the entire branch all the way up to the root node such that the branch
is deleted up to a point where it may be required for other leaf nodes. That
is, no branch should end in a leaf node unless it is of a LeafInfo class,
specified below. Ive enclosed my code (the current state of it anyways!) --
if anyone has any insight on this, please share it with me. THank you -Ike

private void killTheKids(MutableTreeNode nodetokill, int fileno){
      // jTree.collapsePath((TreePath)jTree.getModel().getRoot());
       Enumeration e = nodetokill.children();
       while(e.hasMoreElements()) {
           MutableTreeNode child = (MutableTreeNode) e.nextElement();
           if(child.isLeaf()){
               LeafInfo nodeInfo =(LeafInfo)
(((DefaultMutableTreeNode)child).getUserObject());

               try{
                   if(/*(child.getAllowsChildren() &&
(child.children()==null || child.getChildCount()==0)) || !(child instanceof
LeafInfo)|| */(nodeInfo.fno==fileno)){
                       //System.out.println(child.getClass());
                       nodetokill.remove(child);//child.removeFromParent();
                       child=null;
                       //while if the the parent of nodetokill is either a
leaf or has no more children, remove it
                       MutableTreeNode m = nodetokill;
                       while(m!=null && (m.isLeaf() ||
m.getChildCount()==0)){
                           MutableTreeNode
mm=(MutableTreeNode)m.getParent();
                           if(mm!=null){
                               mm.remove(m);

                           }
                           m=null;
                           m=mm;
                       };
                       return;
                   }
               }catch(Exception ex){
                   ex.printStackTrace();
                   e=null;//to break at
               }

           }else{
               killTheKids(child,fileno);
           }
       }

   }

public class LeafInfo {
       public String LeafName;
       public int fno;
       public long mybyteCount;
       //double distanceFromLeft, /*distanceFromRight,*/ itemHeight,
shelfLength;
       public LeafInfo(String LeafName, int fno, long mybyteCount) {
           this.LeafName = LeafName;
           this.fno=fno;
           this.mybyteCount=mybyteCount;
       }

       public String toString() {
           return LeafName;
       }
   }
Thomas Weidenfeller - 15 Mar 2005 19:23 GMT
> Ive been wrestling for nearly a day with what ought to be a simple
> algorithm. I'm trying to find leafs on a JTree where the data emanates from
[quoted text clipped - 4 lines]
> specified below. Ive enclosed my code (the current state of it anyways!) --
> if anyone has any insight on this, please share it with me. THank you -Ike

First a few general observations:

- You code is as messy as your problem description. Actually, just
dumping this mess onto us, without even cleaning it up and formating it
in a reasonable way is a little bit cheeky. You might want to sit down
for a minute with some pencil and paper and write a simplified
description. I think I know what you want, but I am not 100% sure.

- I don't get the idea of the LeafInfo class. I will ignore it.

- You should make sure that getAllowsChildren() returns correct
information. It should return true for folder-type nodes, and false for
any other data.

> private void killTheKids(MutableTreeNode nodetokill, int fileno){
>        // jTree.collapsePath((TreePath)jTree.getModel().getRoot());
>         Enumeration e = nodetokill.children();

Enumerating and removing nodes at the same time gets you in trouble. The
enumerator makes no guarantee that it will work correctly if you remove
elements while enumerating.

>         while(e.hasMoreElements()) {
>             MutableTreeNode child = (MutableTreeNode) e.nextElement();
>             if(child.isLeaf()){

Here you look ahead in your recursion for no apparent reason.

>                 LeafInfo nodeInfo =(LeafInfo)
> (((DefaultMutableTreeNode)child).getUserObject());
[quoted text clipped - 8 lines]
>                         //while if the the parent of nodetokill is either a
> leaf or has no more children, remove it

This does not make sense. The parent can't be a leaf. A leaf has no
children, if the TreeNode data structure is intact. If you find this in
your tree you have managed to butcher your tree to an extend that the
tree is basically worthless.

>                         MutableTreeNode m = nodetokill;

nodetokill is already a MutableTreeNode. Why are you assigning it to
another reference?

>                         while(m!=null && (m.isLeaf() ||
> m.getChildCount()==0)){
[quoted text clipped - 4 lines]
>
>                             }

In theory this could be replaced with

    m.removeFromParent();

but you are in fact disconnecting your current node from the tree while
still recursing in that branch.

Or in short, something like:

protected boolean canBeRemoved(TreeNode node, ...) {
    return     node.isLeaf() &&
        ( node.getAllowsChildren() // empty folder-type node
         || // no folder, check for special condition
         || // whatever other criteria
         || //    qualifies for removal
        );
}

public boolean removeAll(MutableTreeNode node, ...) {

    int n = node.getChildCount();
    int i = 0;
    while(i < n) {
        if(removeAll((MutableTreeNode)node.getChildAt(i), ...))
        {
            node.remove(i);
            n--;
        } else {
            i++;
        }
    }
    return canBeRemoved(node, ...);
}

Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq

Ike - 15 Mar 2005 20:01 GMT
Thanks Thomas --you;re right, sorry the code has been "dumped," as is --
I've been too close to it thje last few hours to realise that until you
pointed it out. Thanks for your help. -Ike

> - You code is as messy as your problem description. Actually, just
> dumping this mess onto us, without even cleaning it up and formating it
> in a reasonable way is a little bit cheeky. You might want to sit down
> for a minute with some pencil and paper and write a simplified
> description. I think I know what you want, but I am not 100% sure.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.