CSDN博客

img flycatcq

树的说明

发表于2004/6/26 1:28:00  816人阅读

树是由节点构成的,在java中是用DefaultMutableTreeNode类来创建节点。创建的过程很简单,首先
创建一个根节点,然后创建根节点的孩子,让后用add(MutableTreeNodenewChild)方法将孩子节点添加
到父节点中,依次类推


//创建节点
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Java");
DefaultMutableTreeNode books = new DefaultMutableTreeNode("Java书籍");
DefaultMutableTreeNode tools = new DefaultMutableTreeNode("Java开发工具");

//添加子节点
rootNode.add(books);
rootNode.add(tools);

books.add(new DefaultMutableTreeNode("Java高级实例编程"));
books.add(new DefaultMutableTreeNode("Java编程思想"));
books.add(new DefaultMutableTreeNode("Java编程详解"));


tools.add(new DefaultMutableTreeNode("JBuilder"));
tools.add(new DefaultMutableTreeNode("JCreator"));
tools.add(new DefaultMutableTreeNode("Visual J++"));

树模型
跟其他模型一样,树模型用于操作数据,并通知视图进行更新。
TreePath类
void removeNode()
 {
  //获取当前节点路径
  TreePath selectedPath= tree.getSelectionPath();
  if(selectedPath!=null)
  {
   DefaultMutableTreeNode selectedNode;
   DefaultTreeModel treeModel;
   //获取当前节点
   selectedNode=(DefaultMutableTreeNode)selectedPath.getLastPathComponent();
   treeModel=(DefaultTreeModel)tree.getModel();
   //删除节点
   treeModel.removeNodeFromParent(selectedNode);
  }
 }
 void addNode()
 {
  DefaultMutableTreeNode newNode;
  newNode= new DefaultMutableTreeNode(textField.getText());
  //获取当前节点的路径
  TreePath selectedPath=tree.getSelectionPath();
  if(selectedPath!=null)
  {
   DefaultMutableTreeNode selectedNode;
   DefaultTreeModel treeModel;
   //获取当前节点
   selectedNode=(DefaultMutableTreeNode)selectedPath.getLastPathComponent();
   treeModel=(DefaultTreeModel)tree.getModel();
   //增加节点
   treeModel.insertNodeInto(newNode,selectedNode,selectedNode.getChildCount());
  }
 }

0 0

相关博文

我的热门文章

img
取 消
img