将xml的数据写入swing树形结构

前端之家收集整理的这篇文章主要介绍了将xml的数据写入swing树形结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

先简单的粘贴下代码,正在学习java的东西,正好用到swing,算是做个练习。API太多,还没有梳理太清楚,慢慢回顾。

@H_403_4@public @H_403_4@class TreeFrame @H_403_4@extends JFrame {
    @H_403_4@public @H_403_4@static @H_403_4@final @H_403_4@int WIDTH = 1100;
    @H_403_4@public @H_403_4@static @H_403_4@final @H_403_4@int HEIGHT = 615;
    @H_403_4@private @H_403_4@static @H_403_4@int xlocation,ylocation;
    @H_403_4@private @H_403_4@boolean xmlFlag = @H_403_4@false;
    @H_403_4@private JPanel treeArea = @H_403_4@new JPanel();
    @H_403_4@private JPanel buttons = @H_403_4@new JPanel();
    DefaultMutableTreeNode top = @H_403_4@new DefaultMutableTreeNode("行政规划");
    @H_403_4@private JTree menuTree = @H_403_4@new JTree(top);
    @H_403_4@private JTextArea text = @H_403_4@new JTextArea();

    DefaultTreeModel model;
    FileOutputStream fos;
    OutputStreamWriter osw;

    @H_403_4@public TreeFrame(){
        @H_403_4@this.setTitle("省份名称");
        @H_403_4@this.setSize(WIDTH,HEIGHT);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        xlocation = (screenSize.width-WIDTH)/2;
        ylocation = (screenSize.height-HEIGHT)/2;
        @H_403_4@this.setLocation(xlocation,ylocation);
        //设置关闭窗口
        @H_403_4@this.addWindowListener(@H_403_4@new WindowListener() {

            @Override
            @H_403_4@public @H_403_4@void windowOpened(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            @H_403_4@public @H_403_4@void windowIconified(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            @H_403_4@public @H_403_4@void windowDeiconified(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            @H_403_4@public @H_403_4@void windowDeactivated(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            @H_403_4@public @H_403_4@void windowClosing(WindowEvent e) {
                @H_403_4@try {
                    fos=@H_403_4@new FileOutputStream("xml/data.xml");
                    osw=@H_403_4@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();
                } @H_403_4@catch (IOException error) {                   
                    error.printStackTrace();
                }
                System.exit(0);
            }

            @Override
            @H_403_4@public @H_403_4@void windowClosed(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            @H_403_4@public @H_403_4@void windowActivated(WindowEvent e) {
                // TODO Auto-generated method stub

            }
        });
        Container container = @H_403_4@this.getContentPane();
        initTreeJPanel();
        inintButtonJpanel();
        JSplitPane mainFrameSplit = @H_403_4@new JSplitPane();
        mainFrameSplit.setEnabled(@H_403_4@false);
        mainFrameSplit.setLeftComponent(treeArea);
        mainFrameSplit.setRightComponent(text);
        treeArea.add(buttons,BorderLayout.SOUTH);
        container.add(mainFrameSplit);
        @H_403_4@this.setMenuBar(getMenuBar());


    }
    /** * 初始化按键区域 */
    @H_403_4@public @H_403_4@void inintButtonJpanel(){
        model = (DefaultTreeModel)menuTree.getModel();
        JButton addSiblingButton = @H_403_4@new JButton("添加兄弟结点");
        JButton addChildButton = @H_403_4@new JButton("添加孩子结点");
        JButton deleteSelectedButton = @H_403_4@new JButton("删除选中结点");
        JButton editSelectedButton = @H_403_4@new JButton("编辑选中结点");
        buttons.add(addChildButton);
        buttons.add(addSiblingButton);
        buttons.add(deleteSelectedButton);
        buttons.add(editSelectedButton);
        //添加编辑结点的监听
        editSelectedButton.addActionListener(@H_403_4@new ActionListener() {

            @Override
            @H_403_4@public @H_403_4@void actionPerformed(ActionEvent e) {
                TreePath selectedPath = menuTree.getSelectionPath();
                @H_403_4@if(selectedPath!=@H_403_4@null){
                    menuTree.startEditingAtPath(selectedPath);
                }
                text.append("编辑结点:"+selectedPath+"\n");
            }
        });
        //添加删除结点的监听
        deleteSelectedButton.addActionListener(@H_403_4@new ActionListener() {

            @Override
            @H_403_4@public @H_403_4@void actionPerformed(ActionEvent e) {
                TreePath selectedPath = menuTree.getSelectionPath();
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)menuTree.getLastSelectedPathComponent();
                @H_403_4@if (selectedNode!=@H_403_4@null && selectedNode.getParent()!=@H_403_4@null) {
                    model.removeNodeFromParent(selectedNode);
                }
                text.append("删除了一个结点:"+selectedPath+"\n");
            }
        });
        //添加孩子结点的监听
        addChildButton.addActionListener(@H_403_4@new ActionListener() {

            @Override
            @H_403_4@public @H_403_4@void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)menuTree.getLastSelectedPathComponent();
                @H_403_4@if (selectedNode == @H_403_4@null) {
                    @H_403_4@return;
                }

                DefaultMutableTreeNode newNode = @H_403_4@new DefaultMutableTreeNode("新结点");
                selectedNode.add(newNode);
                TreeNode []nodes = model.getPathToRoot(newNode);
                TreePath path = @H_403_4@new TreePath(nodes);
                menuTree.scrollPathToVisible(path);
                menuTree.updateUI();
                text.append("添加了一个结点:"+path+"\n");

            }
        });
        //添加兄弟节点结点的监听
        addSiblingButton.addActionListener(@H_403_4@new ActionListener() {

            @Override
            @H_403_4@public @H_403_4@void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)menuTree.getLastSelectedPathComponent();
                @H_403_4@if (selectedNode == @H_403_4@null) {
                    @H_403_4@return;
                }
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode)selectedNode.getParent();
                @H_403_4@if (parent == @H_403_4@null) {
                    @H_403_4@return;
                }
                DefaultMutableTreeNode newNode = @H_403_4@new DefaultMutableTreeNode("新结点");
                @H_403_4@int selectedIndex = parent.getIndex(selectedNode);
                model.insertNodeInto(newNode,parent,selectedIndex + 1);
                TreeNode []nodes = model.getPathToRoot(newNode);
                TreePath path = @H_403_4@new TreePath(nodes);
                menuTree.scrollPathToVisible(path);
                text.append("添加了一个结点:"+path+"\n");
            }
        });
    }
    /** * 初始化树形结构 */
    @H_403_4@public @H_403_4@void initTreeJPanel(){
        menuTree.setEditable(@H_403_4@true);
        treeArea.setLayout(@H_403_4@new BorderLayout());
        @H_403_4@int mainBorderWidth = getWidth();
        @H_403_4@int mainBorderHeight = getHeight();
        treeArea.setPreferredSize(@H_403_4@new Dimension(mainBorderWidth/4,mainBorderHeight) );
        menuTree.setShowsRootHandles(@H_403_4@true);
        initTreeParam();
        JScrollPane jScrollTree = @H_403_4@new JScrollPane();
        jScrollTree.getViewport().add(menuTree,1);
        treeArea.add(jScrollTree,BorderLayout.CENTER);

    }
    /** * 初始化树形结构数据 */
    @H_403_4@public @H_403_4@void initTreeParam(){
        DefaultMutableTreeNode rootnode = (DefaultMutableTreeNode)menuTree.getModel().getRoot();
        rootnode.removeAllChildren();
        xmlFlag = xmlParser("xml/data.xml",top);
        @H_403_4@if(!xmlFlag){
            @H_403_4@return;
        }@H_403_4@else {
            TreeNode root = (TreeNode)menuTree.getModel().getRoot();
            expandNode(menuTree,@H_403_4@new TreePath(root),@H_403_4@true,@H_403_4@false);
        }
    }
    /** * 展开节点,好像有也可以 * @param tree * @param parent * @param expand * @param expandChildren */
    @H_403_4@private @H_403_4@void expandNode(JTree tree,TreePath parent,@H_403_4@boolean expand,@H_403_4@boolean expandChildren){
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        @H_403_4@if (node.getChildCount()>=0) {
            @H_403_4@for (Enumeration e = node.children();e.hasMoreElements() ;) {
                TreeNode n = (TreeNode)e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                @H_403_4@if (expandChildren) {
                    expandNode(tree,path,expand,expandChildren);
                }
            }
        }
        @H_403_4@if (expand) {
            tree.expandPath(parent);
        }@H_403_4@else {
            tree.collapsePath(parent);
        }
    }
    /** * 将xml结点添加到swing树形结构 * @param path xml路径 * @param top swing树形结构的头结点 * @return */
    @H_403_4@private @H_403_4@boolean xmlParser(String path,DefaultMutableTreeNode top){
        File file = @H_403_4@new File(path);
        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
        @H_403_4@try {
            DocumentBuilder dombuilder = domfac.newDocumentBuilder();
            Document doc = dombuilder.parse(@H_403_4@new FileInputStream(file));
            Element root = doc.getDocumentElement();
            String name = root.getAttribute("name");
            DefaultMutableTreeNode newnode = @H_403_4@new DefaultMutableTreeNode(name);
            top.add(newnode);
            @H_403_4@if (!Recurrence(root,newnode)) {

            }
        } @H_403_4@catch (ParserConfigurationException e) {

            e.printStackTrace();
        } @H_403_4@catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } @H_403_4@catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } @H_403_4@catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        @H_403_4@return @H_403_4@true;
    }
    /** * 遍历xml所有结点 * @param node xml结点 * @param top swing树形结构结点 * @return */
    @H_403_4@private @H_403_4@boolean Recurrence(Node node,DefaultMutableTreeNode top){
        List<Node> list = getElementNode(node);
        DefaultMutableTreeNode snode= @H_403_4@null;
        @H_403_4@if (list.size()==0) {

        } @H_403_4@else {
            @H_403_4@for(Node n : list){
                NamedNodeMap nGetAttributes = n.getAttributes();
                String name = nGetAttributes.getNamedItem("name").getNodeValue();
                snode = @H_403_4@new DefaultMutableTreeNode(name);
                top.add(snode);
                @H_403_4@if (!Recurrence(n,snode)) {
                    @H_403_4@return @H_403_4@false;
                }
            }
        }
        @H_403_4@return @H_403_4@true;
    }
    /** * 找到xml结点的子节点 * @param node xml结点 * @return */
    @H_403_4@private List<Node> getElementNode(Node node){
        List<Node> list = @H_403_4@new LinkedList<Node>();
        @H_403_4@for (Node n = node.getFirstChild();n!=@H_403_4@null;n=n.getNextSibling()) {
            @H_403_4@if (n.getNodeType()==Node.ELEMENT_NODE) {
                list.add(n);
            }
        }
        @H_403_4@return list;
    }
    /** * 将树形结构保存到xml文件中 * @param root 根节点 * @param fw 输出流 */
    @H_403_4@public @H_403_4@void saveToFile(DefaultMutableTreeNode root,OutputStreamWriter osw){
        @H_403_4@try {
            osw.write("<node name=\""+root.toString()+"\">\r\n");
            @H_403_4@for (@H_403_4@int i=0; i < root.getChildCount(); i++){
                DefaultMutableTreeNode childNode =(DefaultMutableTreeNode)root.getChildAt(i);
                saveToFile(childNode,osw);
            }
            osw.write("</node>\r\n");
       }@H_403_4@catch (Exception e){ 
       e.printStackTrace();
      } 
    }
    @H_403_4@public @H_403_4@static @H_403_4@void main(String[] args) {
        TreeFrame mainFrame = @H_403_4@new TreeFrame();
        mainFrame.setResizable(@H_403_4@false);
        mainFrame.setVisible(@H_403_4@true);

    }

}

猜你在找的XML相关文章