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

先简单的粘贴下代码,正在学习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

将xml的数据写入swing树形结构的相关文章

[Swing]树形结构的实现

一般步骤: 1.建立根节点 private DefaultMutableTreeNode root = new DefaultMutableTreeNode("根节点"); 2.建立树形模型 private DefaultTreeModel treeModel = new DefaultTreeModel(root); 3.建立树 private JTree tree = new JTree(treeModel); 4.向树内添加节点 DefaultMutableTreeNode no

通用列表数据转化为树形结构

近期做项目用的是JQuery  easyUI 控件, 尽管非常强大,可是高级控件对于数据的格式要求比較严格遇到 例如以下问题 1.使用comboTree 控件   绑定树形的组织结构   可是 数据库查到的数据格式是 列表形式,并不符合  combotree的数据结构 以下是我的数据和  combotree 数据个对照 通用的数据结构   命名A "[{"UnitID":"7cf57594a7074c46b94dcd6c985b0ced","Un

关于html嵌入xml数据岛如何穿过树形结构关系的问题

作者: 字体:[增加 减小] 类型:转载 html里面引用xml的数据岛,如何穿过树形结构的关系,我不知道这个datafld里面应该如何使用xml里面的标签名称,如何加前缀,如何从resume得到name子元素 如下面的代码细节,html里面引用xml的数据岛,如何穿过树形结构的关系? 我不知道这个datafld里面应该如何使用xml里面的标签名称,如何加前缀,如何从resume得到name子元素?同时我的html文件应该如何修改呢? read.qidian.com/BookReader/144

Silverlight项目笔记7:xml/json数据解析、MVVM下实现多级树形结构TreeView、忽视引用类型导致数据绑定错误、通过流或动态空间加载图片、虚拟目录设置、silverlight安全机制引发的问题、WebClient缓存问题

涉及的内容主要有: 1.xml/json数据解析 2.多级树形结构TreeView 3.忽视引用类型导致数据绑定错误 4.通过流或动态空间加载图片 5.虚拟目录设置 6.silverlight安全机制引发的问题 7.webclient缓存问题 1.xml/json数据解析 (1)xml数据解析 使用WebClient获取数据,获取到的数据实例化为一个XDocument,使用XDocument的Descendants(XName)方法获得对应节点的数据集合,再通过Element这个方法对数据集合进

《程序实现》从xml、txt文件里读取数据写入excel表格

直接上码 import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; impo

将DataSet中的数据写入XML

protected void Button1_Click(object sender, EventArgs e) { string conStr = ConfigurationManager.ConnectionStrings["lianxiConnectionString"].ConnectionString; using (SqlConnection conn=new SqlConnection(conStr)) { conn.Open(); using (SqlCommand c

Atitit.各种 数据类型 ( 树形结构,表形数据 ) 的结构与存储数据库 attilax 总结

Atitit.各种  数据类型 ( 树形结构,表形数据  ) 的结构与存储数据库 attilax  总结 1. 数据结构( 树形结构,表形数据,对象结构 ) 1 2. 编程语言中对应的数据结构 java c# php ( Dic/Map      List    datatable ) 1 3. 数据库存储数据  1 4. 数据的表形显示( 多条记录 与单条记录 ) 2 5. ASP.NET 数据控件:GridView,DataList,Repeater ,DetailsView,FormVie

Delphi中根据分类数据生成树形结构的最优方法

一. 引言:    TreeView控件适合于表示具有多层次关系的数据.它以简洁的界面,表现形式清晰.形象,操作简单而深受用户喜爱.而且用它可以实现ListView.ListBox所无法实现的很多功能,因而受到广大程序员的青睐.    树形结构在Windows环境中被普遍应用,但在数据库开发中面对层次多.结构复杂的数据,如何快速构造树形目录并实现导航呢?    二. 实现关键技术:    在Delphi提供的控件中包含了TreeView控件,但树的具体形成还需要用户编写代码.即它的列表项要在程序

CSS实现树形结构 + js加载数据

看到一款树形结构,比较喜欢它的样式,就参照它的外观自己做了一个,练习一下CSS. 做出来的效果如下: ul,li { list-style-type: none } .tree { display: block; position: relative; padding: 5px 15px } .tree span { display: inline-block; height: 30px; line-height: 28px; min-width: 60px; text-align: cente