Click here to Skip to main content
15,885,004 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to Jtree and Java.

So, I have a tree structure like this :

-Abcd
--Efghi
---Pqrst
---Uvwxyz
---Xyza
---Hdwik
---Lmnop
---Bcdef
--Tqrsp
---Jumak
----Uoaha
----Lobte
-----Cshnt
----Karke

Now i want to get the count of Abcd = 14 (i.e Count of all children of Abcd+1) similarly, Abcd - Efghi = 7 (i.e Count of all leafNodes of Efghi+1)

But I am not able to get the count. Here's the code :

import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import java.io.*;
import java.util.*;

public class treeTest {
    public treeTest(List<String> somelist) {

        DefaultMutableTreeNode root = new DefaultMutableTreeNode(somelist.get(0));


        DefaultTreeModel model = new DefaultTreeModel(root);


        JTree tree = new JTree(model);


        for(int i = 1;i<somelist.size();i++)
        {
        buildTreeFromString(model, somelist.get(i));
        }

// UI


        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(tree);
        f.setSize(300, 300);
        f.setLocation(200, 200);
        f.setVisible(true);

        for (int i = 0; i < tree.getRowCount(); i++) {
        tree.expandRow(i);
        }

        DefaultMutableTreeNode rootNode  = ((DefaultMutableTreeNode)tree.getModel().getRoot());

       int n = tree.getModel().getChildCount(rootNode);
        System.out.println(n);


    }



    private void buildTreeFromString(final DefaultTreeModel model, final String str) {
        // Fetch the root node
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

        // Split the string around the delimiter
        String [] strings = str.split(" - ");

        // Create a node object to use for traversing down the tree as it 
        // is being created
        DefaultMutableTreeNode node = root;

        // Iterate of the string array
        for (String s: strings) {
            // Look for the index of a node at the current level that
            // has a value equal to the current string
            int index = childIndex(node, s);

            // Index less than 0, this is a new node not currently present on the tree
            if (index < 0) {
                // Add the new node
                DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(s);
                node.insert(newChild, node.getChildCount());
                node = newChild;
            }
            // Else, existing node, skip to the next string
            else {
                node = (DefaultMutableTreeNode) node.getChildAt(index);
            }
        }
    }


    private int childIndex(final DefaultMutableTreeNode node, final String childValue) {
        Enumeration<DefaultMutableTreeNode> children = node.children();
        DefaultMutableTreeNode child = null;
        int index = -1;

        while (children.hasMoreElements() && index < 0) {
            child = children.nextElement();

            if (child.getUserObject() != null && childValue.equals(child.getUserObject())) {
                index = node.getIndex(child);
            }
        }

        return index;
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {

          List<String> list = new ArrayList<String>();
          BufferedReader reader = new BufferedReader(new FileReader("Filepath\Sample.txt"));
          String line;
          while ((line = reader.readLine()) != null) {
          list.add(line);
        }
          reader.close();

        new treeTest(list);
    }
}


Is there any way that i could get leafcount of every parent in the tree or is there any other way to get that information without using tree?

What I have tried:

I have tried creating a Jtree.
Posted
Updated 24-Jun-17 12:41pm
v2
Comments
Patrice T 18-Jun-17 13:19pm    
I wouldn't use a tree for this problem, it just complicate things.
Member 13265840 24-Jun-17 2:03am    
Then what should i do, can you help me

1 solution

ppolymorphe wrote:
I wouldn't use a tree for this problem, it just complicate things.

Quote:
Then what should i do, can you help me

That is a matter of "problem analyze" : you can build a tree, but do you need to ?
As you have already found, you need to read lines 1 by 1
Java
while ((line = reader.readLine()) != null) {
  // your code for a line goes here.
}

When you have this line: "Abcd - Tqrsp - Jumak - Lobte"
You are required to count how many times you have seen each substring as:
"Abcd - Tqrsp - Jumak - Lobte"
"Abcd - Tqrsp - Jumak"
"Abcd - Tqrsp"
"Abcd"
As you get strings, you need to remember each couples of string (key) and counter.
The most simple solution is an array for keys and an array to counters, it will not scale well, but it will do what you need.
For a more efficient solution,some languages have associative arrays, Java have hashmaps.

How to get each substring ?
you already use split:
Java
// Split the string around the delimiter
String [] strings = str.split(" - ");

When you need something more sophisticated, go RegEx (Regular Expressions)
This RegEx will drop the last part of a string "^(.+)\s-\s[^-]+$"

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]

Nota: I am not a Java programmer, I am just a programmer.
 
Share this answer
 
v2
Comments
Member 13265840 24-Jun-17 18:42pm    
Thank You, I used hashmap to get the answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900