先简单的粘贴下代码,正在学习java的东西,正好用到swing,算是做个练习。API太多,还没有梳理太清楚,慢慢回顾。
public class TreeFrame extends JFrame { public static final int WIDTH = 1100; public static final int HEIGHT = 615; private static int xlocation ,ylocation; private boolean xmlFlag = false; private JPanel treeArea = new JPanel(); private JPanel buttons = new JPanel(); DefaultMutableTreeNode top = new DefaultMutableTreeNode("行政规划"); private JTree menuTree = new JTree(top); private JTextArea text = new JTextArea(); DefaultTreeModel model; FileOutputStream fos; OutputStreamWriter osw; public TreeFrame(){ this.setTitle("省份名称"); this.setSize(WIDTH, HEIGHT); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); xlocation = (screenSize.width-WIDTH)/2; ylocation = (screenSize.height-HEIGHT)/2; this.setLocation(xlocation, ylocation); //设置关闭窗口 this.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent e) { try { fos=new FileOutputStream("xml/data.xml"); osw=new OutputStreamWriter(fos,"utf-8"); osw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+"\r\n"); model = (DefaultTreeModel)menuTree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot(); //头结点行政规划不用保存 saveToFile(root.getNextNode(), osw); osw.close(); fos.close(); } catch (IOException error) { error.printStackTrace(); } System.exit(0); } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } }); Container container = this.getContentPane(); initTreeJPanel(); inintButtonJpanel(); JSplitPane mainFrameSplit = new JSplitPane(); mainFrameSplit.setEnabled(false); mainFrameSplit.setLeftComponent(treeArea); mainFrameSplit.setRightComponent(text); treeArea.add(buttons,BorderLayout.SOUTH); container.add(mainFrameSplit); this.setMenuBar(getMenuBar()); } /** * 初始化按键区域 */ public void inintButtonJpanel(){ model = (DefaultTreeModel)menuTree.getModel(); JButton addSiblingButton = new JButton("添加兄弟结点"); JButton addChildButton = new JButton("添加孩子结点"); JButton deleteSelectedButton = new JButton("删除选中结点"); JButton editSelectedButton = new JButton("编辑选中结点"); buttons.add(addChildButton); buttons.add(addSiblingButton); buttons.add(deleteSelectedButton); buttons.add(editSelectedButton); //添加编辑结点的监听 editSelectedButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath selectedPath = menuTree.getSelectionPath(); if(selectedPath!=null){ menuTree.startEditingAtPath(selectedPath); } text.append("编辑结点:"+selectedPath+"\n"); } }); //添加删除结点的监听 deleteSelectedButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath selectedPath = menuTree.getSelectionPath(); DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)menuTree.getLastSelectedPathComponent(); if (selectedNode!=null && selectedNode.getParent()!=null) { model.removeNodeFromParent(selectedNode); } text.append("删除了一个结点:"+selectedPath+"\n"); } }); //添加孩子结点的监听 addChildButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)menuTree.getLastSelectedPathComponent(); if (selectedNode == null) { return; } DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("新结点"); selectedNode.add(newNode); TreeNode []nodes = model.getPathToRoot(newNode); TreePath path = new TreePath(nodes); menuTree.scrollPathToVisible(path); menuTree.updateUI(); text.append("添加了一个结点:"+path+"\n"); } }); //添加兄弟节点结点的监听 addSiblingButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)menuTree.getLastSelectedPathComponent(); if (selectedNode == null) { return; } DefaultMutableTreeNode parent = (DefaultMutableTreeNode)selectedNode.getParent(); if (parent == null) { return; } DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("新结点"); int selectedIndex = parent.getIndex(selectedNode); model.insertNodeInto(newNode, parent, selectedIndex + 1); TreeNode []nodes = model.getPathToRoot(newNode); TreePath path = new TreePath(nodes); menuTree.scrollPathToVisible(path); text.append("添加了一个结点:"+path+"\n"); } }); } /** * 初始化树形结构 */ public void initTreeJPanel(){ menuTree.setEditable(true); treeArea.setLayout(new BorderLayout()); int mainBorderWidth = getWidth(); int mainBorderHeight = getHeight(); treeArea.setPreferredSize(new Dimension(mainBorderWidth/4,mainBorderHeight) ); menuTree.setShowsRootHandles(true); initTreeParam(); JScrollPane jScrollTree = new JScrollPane(); jScrollTree.getViewport().add(menuTree, 1); treeArea.add(jScrollTree,BorderLayout.CENTER); } /** * 初始化树形结构数据 */ public void initTreeParam(){ DefaultMutableTreeNode rootnode = (DefaultMutableTreeNode)menuTree.getModel().getRoot(); rootnode.removeAllChildren(); xmlFlag = xmlParser("xml/data.xml", top); if(!xmlFlag){ return; }else { TreeNode root = (TreeNode)menuTree.getModel().getRoot(); expandNode(menuTree,new TreePath(root),true,false); } } /** * 展开节点,好像有也可以 * @param tree * @param parent * @param expand * @param expandChildren */ private void expandNode(JTree tree,TreePath parent,boolean expand,boolean expandChildren){ 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); if (expandChildren) { expandNode(tree, path, expand, expandChildren); } } } if (expand) { tree.expandPath(parent); }else { tree.collapsePath(parent); } } /** * 将xml结点添加到swing树形结构 * @param path xml路径 * @param top swing树形结构的头结点 * @return */ private boolean xmlParser(String path,DefaultMutableTreeNode top){ File file = new File(path); DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder dombuilder = domfac.newDocumentBuilder(); Document doc = dombuilder.parse(new FileInputStream(file)); Element root = doc.getDocumentElement(); String name = root.getAttribute("name"); DefaultMutableTreeNode newnode = new DefaultMutableTreeNode(name); top.add(newnode); if (!Recurrence(root,newnode)) { } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } /** * 遍历xml所有结点 * @param node xml结点 * @param top swing树形结构结点 * @return */ private boolean Recurrence(Node node,DefaultMutableTreeNode top){ List<Node> list = getElementNode(node); DefaultMutableTreeNode snode= null; if (list.size()==0) { } else { for(Node n : list){ NamedNodeMap nGetAttributes = n.getAttributes(); String name = nGetAttributes.getNamedItem("name").getNodeValue(); snode = new DefaultMutableTreeNode(name); top.add(snode); if (!Recurrence(n, snode)) { return false; } } } return true; } /** * 找到xml结点的子节点 * @param node xml结点 * @return */ private List<Node> getElementNode(Node node){ List<Node> list = new LinkedList<Node>(); for (Node n = node.getFirstChild();n!=null;n=n.getNextSibling()) { if (n.getNodeType()==Node.ELEMENT_NODE) { list.add(n); } } return list; } /** * 将树形结构保存到xml文件中 * @param root 根节点 * @param fw 输出流 */ public void saveToFile(DefaultMutableTreeNode root, OutputStreamWriter osw){ try { osw.write("<node name=\""+root.toString()+"\">\r\n"); for (int i=0; i < root.getChildCount(); i++){ DefaultMutableTreeNode childNode =(DefaultMutableTreeNode)root.getChildAt(i); saveToFile(childNode, osw); } osw.write("</node>\r\n"); }catch (Exception e){ e.printStackTrace(); } } public static void main(String[] args) { TreeFrame mainFrame = new TreeFrame(); mainFrame.setResizable(false); mainFrame.setVisible(true); } }
xml文件结构:
时间: 2024-11-12 01:30:46