读取xml文件,实现JTree树形结构的构建(一) 淡淡的烟草味﹌ 2024-04-08 08:59 14阅读 0赞 JTree是Swing的一个组件(树),一颗树由若干节点,通过层级关系组成。 在java中JTree的节点通过DefaultMutableTreeNode类创建,该类实现TreeNode接口。 目前我只会一点基础的应用 例如使用DefaultMutableTreeNode类构建树形结构。 下面是一个简单的demo,先来结果图,再看代码! 结果图: ![在这里插入图片描述][cb4c565dbb414dce8e139a1a93abfab6.png] 代码: public class ReadBook { JTree jTree; public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException { ReadBook readBook = new ReadBook(); readBook.readXml(); readBook.JFConstruct(); } public void readXml() throws ParserConfigurationException, IOException, SAXException { //MyMutableTreeNode类是我继承的DefaultMutableTreeNode类,因为我要根据我自己的需求进行的扩展,所以编写了该类 // 下面会给出MyMutableTreeNode类的代码 //这个节点是自己创建的根节点,第一个参数表示节点的名称,第二个参数是节点的描述 //一般情况下,使用者可以直接使用DefaultMutableTreeNode类进行节点对象的创建 // DefaultMutableTreeNode root = new DefaultMutableTreeNode("data"); MyMutableTreeNode root = new MyMutableTreeNode("data", "这个是根节点"); //你自己的路径,即xml文件路径 String path = "你自己的路径xxxxxxxxxx/xml/book.xml"; // 创建解析器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); // 创建一个Document对象 Document doc = db.parse(path); //去除xml文件中的转行符,如果不去除,在后面获取节点的时候,dom读取会多获得节点 initDoc(doc); NodeList bookList = doc.getElementsByTagName("book"); // 获取节点个数 System.out.println("一共有" + bookList.getLength() + "本书"); //在这儿可以创建一个节点的数组,即表示每本书的根节点,后面都添加到root根节点上 MyMutableTreeNode[] secondaryRoot = new MyMutableTreeNode[bookList.getLength()]; // 遍历每个book节点 for (int i = 0; i < bookList.getLength(); i++) { System.out.println("*******************************"); // 索引从零开始 org.w3c.dom.Node book = bookList.item(i); secondaryRoot[i] = new MyMutableTreeNode("book" + i); root.add(secondaryRoot[i]); // 获取book节点所有属性集合 org.w3c.dom.NamedNodeMap attrs = book.getAttributes(); System.out.println("第" + (i + 1) + "本书共有" + attrs.getLength() + "属性"); NodeList childNodes = book.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node item = childNodes.item(j); NodeList childNodes1 = item.getChildNodes(); for (int k = 0; k < childNodes1.getLength(); k++) { System.out.println(childNodes1.item(k).getNodeValue()); MyMutableTreeNode treeNode = new MyMutableTreeNode(childNodes1.item(k).getNodeValue()); secondaryRoot[i].add(treeNode); } } } jTree = new JTree(root); // TreeNode node = (TreeNode) jTree.getModel().getRoot(); //展开所有节点 expandAll(jTree, new TreePath(node), true); } private void initDoc(org.w3c.dom.Node node)//将doc中的所有\n节点去除,提高处理效率 { short nodeType = node.getNodeType(); org.w3c.dom.Node parent; switch (nodeType) { case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE: break; case org.w3c.dom.Node.TEXT_NODE: if (node.getNodeValue().trim().equals("")) { parent = node.getParentNode(); parent.removeChild(node); node = parent; } break; case org.w3c.dom.Node.ELEMENT_NODE: break; default: break; } org.w3c.dom.Node child = node.getFirstChild(); while (null != child) { initDoc(child); child = child.getNextSibling(); } } public void JFConstruct(){ JFrame f = new JFrame("TreeTest"); Container contentPane = f.getContentPane(); //创建的一个滚动条 JScrollPane scrollPane = new JScrollPane(); //创建的一个面板 JPanel panel = new JPanel(); //将面板和滚动条添加到JFrame f容器中 contentPane.add(panel, BorderLayout.NORTH); contentPane.add(scrollPane, BorderLayout.CENTER); //给JTree添加一个滚动条,并添加到JFrame f容器中 f.add(new JScrollPane(jTree)); f.pack(); f.setExtendedState(JFrame.MAXIMIZED_BOTH); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } book.xml文件内容如下: <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book id="1"> <name>冰与火之歌</name> <author>乔治马丁</author> <year>2014</year> <price>89</price> </book> <book id="2"> <name>安徒生童话</name> <year>2004</year> <price>77</price> <language>English</language> </book> </bookstore> 以上得到的结果叶子结点没有展开,可以通过添加下面的代码,来直接打开。注意要把对应的调用代码打开。 ![记得打开][75393297537f4f1f9c58cc3003c50ff5.png] /******************************************** * 展开所有树节点 * @param tree 当前数 * @param parent 父节点的路径 * @param expand 是否展开 true为展开 */ private void expandAll(JTree tree, TreePath parent, boolean expand) { TreeNode node = (TreeNode) parent.getLastPathComponent(); if (node.getChildCount() > 0) { for (Enumeration e = node.children(); e.hasMoreElements(); ) { TreeNode n = (TreeNode) e.nextElement(); TreePath path = parent.pathByAddingChild(n); expandAll(tree, path, expand); } } if (expand) { tree.expandPath(parent); } else { tree.collapsePath(parent); } } 现在的效果图为: ![在这里插入图片描述][3b88fb15e8114e8cb2dbb5ba066cf339.png] [cb4c565dbb414dce8e139a1a93abfab6.png]: https://image.dandelioncloud.cn/pgy_files/images/2024/04/08/bfb28597db2a4919b18e6f5027ea3fed.png [75393297537f4f1f9c58cc3003c50ff5.png]: https://image.dandelioncloud.cn/pgy_files/images/2024/04/08/f95a5b118d9244a285ea30862ba24353.png [3b88fb15e8114e8cb2dbb5ba066cf339.png]: https://image.dandelioncloud.cn/pgy_files/images/2024/04/08/71aba42281574d25b0820326bed74af3.png
还没有评论,来说两句吧...