我是Java的初学者。我正在尝试使用DOM解析器从XML文件(在本例中为helloWorld.xml)中动态填充JTree。我从流动的线程Creating a JTree out of an XML document using DOM parser
中获取了我的代码的帮助package java_img_parser.jtrees;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLTree extends JTree {
DefaultTreeModel dm;
JTree tree = new JTree(dm);
public XMLTree() throws SAXException, IOException {
this.dm = treeBuilder();
}
public DefaultTreeModel treeBuilder() throws SAXException, IOException{
Node root = null;
DefaultTreeModel dtModel = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("helloWorld.xml");
root = (Node)doc.getDocumentElement();
} catch (ParserConfigurationException ex) {
Logger.getLogger(XMLTree.class.getName()).log(Level.SEVERE, null, ex);
}
if(root != null){
dtModel = new DefaultTreeModel(makeTree(root));
dtModel.reload();
}
return dtModel;
}
private DefaultMutableTreeNode makeTree(Node root){
DefaultMutableTreeNode rootTreeNode;
rootTreeNode = new DefaultMutableTreeNode(root.getNodeName());
NodeList nodeList = root.getChildNodes();
for(int count=0;count<nodeList.getLength();count++){
Node tempNode = nodeList.item(count);
if(tempNode.getNodeType() == Node.ELEMENT_NODE){
if(tempNode.hasChildNodes()){
rootTreeNode.add(makeTree(tempNode));
}
}
}
System.out.println("Child-Node of"+root.getParentNode()+"is"+root.getChildNodes());
return rootTreeNode;
}
public static void main(String args[]) throws SAXException, IOException{
JFrame myFrame = new JFrame();
myFrame.setTitle("XmlJTreeExample");
myFrame.setSize(300, 500);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
XMLTree myTree = new XMLTree();
System.out.println("Height of this JTree is:" + myTree.tree.getHeight());
myFrame.add(myTree.tree);
myFrame.setVisible(true);
}
}
当我执行println()时,我可以看到正在遍历子节点。但是相同的节点没有被添加到我的JTree中(它显示零(0)高度)。
我的源XML文件与上面的帖子相同:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE people SYSTEM "validator.dtd">
<people>
<student>
<name>John</name>
<course>Computer Technology</course>
<semester>6</semester>
<scheme>E</scheme>
</student>
<student>
<name>Foo</name>
<course>Industrial Electronics</course>
<semester>6</semester>
<scheme>E</scheme>
</student>
</people>
我得到的输出是一个空白的JFrame,这在输出控制台中: 运行:
Child-Node of[student: null]is[name: null]
Child-Node of[student: null]is[course: null]
Child-Node of[student: null]is[semester: null]
Child-Node of[student: null]is[scheme: null]
Child-Node of[people: null]is[student: null]
Child-Node of[student: null]is[name: null]
Child-Node of[student: null]is[course: null]
Child-Node of[student: null]is[semester: null]
Child-Node of[student: null]is[scheme: null]
Child-Node of[people: null]is[student: null]
Child-Node of[#document: null]is[people: null]
Height of this JTree is:0
BUILD SUCCESSFUL (total time: 23 seconds)
答案 0 :(得分:1)
Swing围绕模型展开,模特为王。基本上,您希望根据您尝试制作的结构将XML内容加载到TreeModel
。
加载模型后,将其应用于JTree
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TestTree {
public static void main(String[] args) {
new TestTree();
}
public TestTree() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultMutableTreeNode root = new DefaultMutableTreeNode("People");
DefaultTreeModel model = new DefaultTreeModel(root);
loadXMLDocument(root);
JTree tree = new JTree(model);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.expandPath(new TreePath(root));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected Node getNodeFrom(Node node, String query) throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xExpress = xPath.compile(query);
return (Node)xExpress.evaluate(node, XPathConstants.NODE);
}
protected NodeList getNodesFrom(Node node, String query) throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xExpress = xPath.compile(query);
return (NodeList)xExpress.evaluate(node, XPathConstants.NODESET);
}
protected void loadXMLDocument(DefaultMutableTreeNode parent) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getClass().getResourceAsStream("/People.xml"));
Node root = (Node) doc.getDocumentElement();
NodeList students = getNodesFrom(root, "/people/student");
for (int index = 0; index < students.getLength(); index++) {
Node studentNode = students.item(index);
DefaultMutableTreeNode studentTreeNode = new DefaultMutableTreeNode("Student");
Node name = getNodeFrom(studentNode, "name");
Node course = getNodeFrom(studentNode, "course");
Node semester = getNodeFrom(studentNode, "semester");
Node scheme = getNodeFrom(studentNode, "scheme");
studentTreeNode.setUserObject(name.getTextContent());
studentTreeNode.add(new DefaultMutableTreeNode("Course: " + course.getTextContent()));
studentTreeNode.add(new DefaultMutableTreeNode("Semester: " + semester.getTextContent()));
studentTreeNode.add(new DefaultMutableTreeNode("Scheme: " + scheme.getTextContent()));
parent.add(studentTreeNode);
}
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
ex.printStackTrace();
}
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
}
仔细查看How to Use Trees了解更多详情