我正在使用 NetBeans 用 Java 开发一个小型桌面应用程序。在某些时候,我需要从 XML 文件读取数据,读取后我需要将其存储在自定义类的对象中。我成功地完成了上述任务(即我读取 XML 数据并将该数据存储在我的自定义类的对象中)。现在我想用该对象填充 JTree。假设我的 XML 如下所示:
<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>
现在我希望我的树看起来像这样
Employees
Permanent Employees
Emp1_Name
Emp2_Name
Part Time Employees
Emp1_Name
Emp2_Name
最佳答案
这可能对您有用:
http://www.arsitech.com/xml/jdom_xml_jtree.php
http://www.wsoftware.de/SpeedJG/XMLTreeView.html
代码取自: 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;
}
关于java - Netbeans:如何动态填充 JTree?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7831034/