2

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
kleopatra
  • 51,061
  • 28
  • 99
  • 211
Jame
  • 21,150
  • 37
  • 80
  • 107
  • *"Netbeans: How to populate JTree Dynamically?"* You'd do it in Netbeans pretty much the same way you'd do it in Java. As to how to do it in Java, see the [FileBro code](http://codereview.stackexchange.com/questions/4446/file-browser-gui), which builds a tree of the file system dynamically. – Andrew Thompson Oct 20 '11 at 04:12

2 Answers2

2

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;         
}
Community
  • 1
  • 1
gtiwari333
  • 24,554
  • 15
  • 75
  • 102
1

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)
Mike
  • 1,889
  • 5
  • 26
  • 32