Jame
Jame

Reputation: 22200

Netbeans: How to populate JTree Dynamically?

I am developing a small desktop application in Java using NetBeans. At some point i need to read data from XML file and after reading that i need to store that in object of my custom class. I sucessfully did the above mentioned task (i.e I read XML data and store that data in object of my custom class). Now i want to populate a JTree with that object. Suppose my XML looks like this:

<Employees>
    <Classification type="permanent">
        <Emp>
            <name>Emp1_Name<name/>
        </Emp>
        <Emp>
            <name>Emp2_Name<name/>
        </Emp>    </Classification>
    <Classification type="part time">
        <Emp>
            <name>Emp1_Name<name/>
        </Emp>
        <Emp>
            <name>Emp2_Name<name/>
        </Emp>    </Classification>
    </Classification>
</Employees>

Now i want my tree to look like this

Employees
    Permanent Employees
        Emp1_Name
        Emp2_Name
    Part Time Employees
        Emp1_Name
        Emp2_Name

Upvotes: 2

Views: 2996

Answers (2)

Mike
Mike

Reputation: 1899

You need to write the function to fetch the information of your application object, You can use SAX or DOM parser for that

    DefaultMutableTreeNode root = new DefaultMutableTreeNode()
    Object object = //function to fetch the information of your Object
// if you are storing all objects in a vector then read element of object
    root.add((DefaultMutableTreeNode)object)

Upvotes: 1

gtiwari333
gtiwari333

Reputation: 25174

This might be useful for you :

http://www.arsitech.com/xml/jdom_xml_jtree.php

http://www.wsoftware.de/SpeedJG/XMLTreeView.html

Code Taken From : Java: How to display an XML file in a JTree

public JTree build(String pathToXml) throws Exception {
     SAXReader reader = new SAXReader();
     Document doc = reader.read(pathToXml);
     return new JTree(build(doc.getRootElement()));
}

public DefaultMutableTreeNode build(Element e) {
   DefaultMutableTreeNode result = new DefaultMutableTreeNode(e.getText());
   for(Object o : e.elements()) {
      Element child = (Element) o;
      result.add(build(child));
   }

   return result;         
}

Upvotes: 2

Related Questions