java 动态的给树添加新节点 望高手指点啊

java 动态的给树添加新节点 望高手指点啊,第1张

//先选中节点才能增加节点

import java.awt.*

import java.awt.event.*

import javax.swing.*

import javax.swing.event.*

import javax.swing.tree.*

public class TreeTest implements ActionListener,TreeModelListener{

JLabel label=null

JTree tree=null

DefaultTreeModel treeModel=null

String nodeName=null//原有节点名称

public TreeTest(){

JFrame f=new JFrame("TreeTest")

Container contentPane=f.getContentPane()

DefaultMutableTreeNode root=new DefaultMutableTreeNode("资源管理器")

tree=new JTree(root)

tree.setEditable(true)

tree.addMouseListener(new MouseHandle())

treeModel=(DefaultTreeModel)tree.getModel()

treeModel.addTreeModelListener(this)

JScrollPane scrollPane=new JScrollPane()

scrollPane.setViewportView(tree)

JPanel panel=new JPanel()

JButton b=new JButton("新增节点")

b.addActionListener(this)

panel.add(b)

b=new JButton("删除节点")

b.addActionListener(this)

panel.add(b)

b=new JButton("清除所有节点")

b.addActionListener(this)

panel.add(b)

label=new JLabel("Action")

contentPane.add(panel,BorderLayout.NORTH)

contentPane.add(scrollPane,BorderLayout.CENTER)

contentPane.add(label,BorderLayout.SOUTH)

f.pack()

f.setVisible(true)

f.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0)

}

})

}

//本方法运行新增、删除、清除所有节点的程序代码.

public void actionPerformed(ActionEvent ae){

if (ae.getActionCommand().equals("新增节点")){

DefaultMutableTreeNode parentNode=null

DefaultMutableTreeNode newNode=new DefaultMutableTreeNode("新节点")

newNode.setAllowsChildren(true)

TreePath parentPath=tree.getSelectionPath()

//取得新节点的父节点

parentNode=(DefaultMutableTreeNode)(parentPath.getLastPathComponent())

//由DefaultTreeModel的insertNodeInto()方法增加新节点

treeModel.insertNodeInto(newNode,parentNode,parentNode.getChildCount())

//tree的scrollPathToVisible()方法在使Tree会自动展开文件夹以便显示所加入的新节点。若没加这行则加入的新节点

//会被 包在文件夹中,你必须自行展开文件夹才看得到。

tree.scrollPathToVisible(new TreePath(newNode.getPath()))

label.setText("新增节点成功")

}

if (ae.getActionCommand().equals("删除节点")){

TreePath treepath=tree.getSelectionPath()

if (treepath!=null){

//下面两行取得选取节点的父节点.

DefaultMutableTreeNode selectionNode=(DefaultMutableTreeNode)treepath.getLastPathComponent()

TreeNode parent=(TreeNode)selectionNode.getParent()

if (parent!=null) {

//由DefaultTreeModel的removeNodeFromParent()方法删除节点,包含它的子节点。

treeModel.removeNodeFromParent(selectionNode)

label.setText("删除节点成功")

}

}

}

if (ae.getActionCommand().equals("清除所有节点")){

//下面一行,由DefaultTreeModel的getRoot()方法取得根节点.

DefaultMutableTreeNode rootNode=(DefaultMutableTreeNode)treeModel.getRoot()

//下面一行删除所有子节点.

rootNode.removeAllChildren()

//删除完后务必运行DefaultTreeModel的reload() *** 作,整个Tree的节点才会真正被删除.

treeModel.reload()

label.setText("清除所有节点成功")

}

}

public void treeNodesChanged(TreeModelEvent e){

TreePath treePath=e.getTreePath()

DefaultMutableTreeNode node=(DefaultMutableTreeNode)treePath.getLastPathComponent()

try{

int[] index=e.getChildIndices()

node=(DefaultMutableTreeNode)node.getChildAt(index[0])

}catch(NullPointerException exc){}

label.setText(nodeName+"更改数据为:"+(String)node.getUserObject())

}

public void treeNodesInserted(TreeModelEvent e){

System.out.println("new node insered")

}

public void treeNodesRemoved(TreeModelEvent e){

System.out.println("node deleted")

}

public void treeStructureChanged(TreeModelEvent e){

System.out.println("Structrue changed")

}

public static void main(String[] args){

new TreeTest()

}

class MouseHandle extends MouseAdapter{

public void mousePressed(MouseEvent e){

try{

JTree tree=(JTree)e.getSource()

int rowLocation=tree.getRowForLocation(e.getX(),e.getY())

TreePath treepath=tree.getPathForRow(rowLocation)

TreeNode treenode=(TreeNode)treepath.getLastPathComponent()

nodeName=treenode.toString()

}catch(NullPointerException ne){}

}

}

}

</script>

    <!--表格树js -->

    <script>

        $(function(){

              

            var setting = {

               

                view:{showLine:true, showIcon: false}, //有没有连线和显不示显示图标

               //下面语句可以让pid相同的分层

                data: {

                    simpleData: {

                        enable: true //自动成圣树结构

                    }

                },

                callback: {

            onClick: zTreeOnClick //回调点击函数

        }

            }    

           

            //动态获取数据自动生成树

            $.ajax({

                type: "post",

                url: "../tools/admin_ajax.ashx?action=GetCallContent&time=" + Math.random(),//链接地址

                dataType: "html",

                success: function (data) {

                    //转换一下json

                    var myNodes = JSON.parse(data)

                    var zNodes = []

                  //  alert(myNodes)

                    for (var i = 0 i < myNodes.length i++) {    //判断                 

                        if (myNodes[i].open != null) {

                            if (myNodes[i].checked != null && myNodes[i].checked )

                                zNodes[i] = { id: myNodes[i].id, pId: myNodes[i].pId, name: myNodes[i].name, answer:myNodes[i].answer, open: true, checked: true }

                            else

                                zNodes[i] = { id: myNodes[i].id, pId: myNodes[i].pId, name: myNodes[i].name, answer:myNodes[i].answer, open: true }

                        }

                        else {

                            if (myNodes[i].checked != null && myNodes[i].checked )

                                zNodes[i] = { id: myNodes[i].id, pId: myNodes[i].pId, name: myNodes[i].name, answer:myNodes[i].answer, checked: true }

                            else

                                zNodes[i] = { id: myNodes[i].id, pId: myNodes[i].pId, name: myNodes[i].name, answer:myNodes[i].answer,}

                        }

                    }

                    $.fn.zTree.init($("#demoZtree"), setting, zNodes)//初始化树

                    $.fn.zTree.getZTreeObj("#demoZtree")//把得到的树赋给div

                }

            })

           //动态生成树的 ztree子节点点击事件

            function zTreeOnClick(event, treeId, treeNode) {

                // alert(treeNode.tId + ", " + treeNode.name)

                $("#eventProblemDesc1").html(treeNode.name)//把标题赋值给div

               

               //插入节点到右边的框内   $("#tab_content_ztree_explain").html(treeNode.name+':')

                $.ajax({

                    type: "get",

                    url: "../tools/admin_ajax.ashx?action=GetCallContent&time=" + Math.random(),

                    dataType: "html",

                    success: function (data) {

                        //转换一下

                        var myNodes = JSON.parse(data)

                        var zNodes = []

                        //利用Selected获取 zTree 当前被选中的节点数据集合

                        var treeObj = $.fn.zTree.getZTreeObj("demoZtree")

                        var nodes = treeObj.getSelectedNodes()

                       

                       // console.log(nodes)

                        for (var i = 0 i < myNodes.length i++) { 

                            var item = myNodes[i]

                            if(item.id == nodes[0].id){  //<span style="font-family: Arial, Helvetica, sans-serif">判断树节点与点击的节点对应的id是否相等</span>

                                   //  alert(item)

                                    var cont = '' 

                                    cont+=item.answer 

                                    $('#tab_content_ztree_explain').html(cont) //赋值给div

                         

                                   

                                   // $('treeNode.name').html(answ) 

                            }

                        }

                    }

                })

            }

      

        })

    </script>

叶子节点:没有孩子节点的节点也就是说,当我们明白了叶子节点的定义后,只需要遍历一遍二叉树,把符合这种条件(左孩子节点和右孩子节点都为NULL的节点)的节点统计出来就可以了。于是,实际上这个问题也就转化成了如何遍历二叉树?很显然,遍历二叉树是可以有多种方式的,如:前序遍历(递归/非递归)、中序遍历(递归/非递归)、后序遍历(递归/非递归)、层次遍历等等。下面我将给出使用递归前序遍历以及层次遍历两种思路实现的求解叶子节点的示例代码吧,仅供参考。其他几种实现方式思路类似,可自行尝试。示例代码如下:package cn.zifangsky.tree.questionsimport org.junit.Testimport cn.zifangsky.queue.LinkQueueimport cn.zifangsky.tree.BinaryTreeNode/** * 求二叉树中叶子节点的个数 * @author Administrator * */public class Question2 {/** * 通过递归前序遍历获取叶子节点个数 * @param root * @return */public int getNumberOfLeavesByPreOrder(BinaryTreeNode root){if(root == null){return 0}else{if(root.getLeft() == null &&root.getRight() == null){ //叶子节点return 1}else{return getNumberOfLeavesByPreOrder(root.getLeft()) + getNumberOfLeavesByPreOrder(root.getRight())}}}/** * 使用层次遍历获取二叉树叶子节点个数 * * @时间复杂度 O(n) * @param root */public int getNumberOfLeavesByQueue(BinaryTreeNode root){int count = 0//叶子节点总数LinkQueue queue = new LinkQueue()if(root != null){queue.enQueue(root)}while (!queue.isEmpty()) {BinaryTreeNode temp = (BinaryTreeNode) queue.deQueue()//叶子节点:左孩子节点和右孩子节点都为NULL的节点if(temp.getLeft() == null &&temp.getRight() == null){count++}else{if(temp.getLeft() != null){queue.enQueue(temp.getLeft())}if(temp.getRight() != null){queue.enQueue(temp.getRight())}}}return count}/** * 测试用例 */@Testpublic void testMethods(){/** * 使用队列构造一个供测试使用的二叉树 * 1 * 23 * 4 5 6 7 * 8 9 */LinkQueue queue = new LinkQueue()BinaryTreeNode root = new BinaryTreeNode(1)//根节点queue.enQueue(root)BinaryTreeNode temp = nullfor(int i=2i */public class LinkQueue{private SinglyNode frontNode//队首节点private SinglyNode rearNode//队尾节点public LinkQueue() {frontNode = nullrearNode = null}/** * 返回队列是否为空 * @时间复杂度 O(1) * @return */public boolean isEmpty(){return (frontNode == null)}/** * 返回存储在队列的元素个数 * @时间复杂度 O(n) * @return */public int size(){int length = 0SinglyNode currentNode = frontNodewhile (currentNode != null) {length++currentNode = currentNode.getNext()}return length}/** * 入队:在链表表尾插入数据 * @时间复杂度 O(1) * @param data */public void enQueue(K data){SinglyNode newNode = new SinglyNode(data)if(rearNode != null){rearNode.setNext(newNode)}rearNode = newNodeif(frontNode == null){frontNode = rearNode}}/** * 出队:删除表头节点 * @时间复杂度 O(1) * @return */public Object deQueue(){if(isEmpty()){throw new RuntimeException("Queue Empty!")}else{Object result = frontNode.getData()if(frontNode == rearNode){frontNode = nullrearNode = null}else{frontNode = frontNode.getNext()}return result}}}单链表节点SinglyNode的定义:package cn.zifangsky.linkedlist/** * 单链表的定义 * @author zifangsky * @param */public class SinglyNode {private K data// 数据private SinglyNode next// 该节点的下个节点public SinglyNode(K data) {this.data = data}public SinglyNode(K data, SinglyNode next) {this.data = datathis.next = next}public K getData() {return data}public void setData(K data) {this.data = data}public SinglyNode getNext() {return next}public void setNext(SinglyNode next) {this.next = next}@Overridepublic String toString() {return "SinglyNode [data=" + data + "]"}}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/10000151.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存