JTree使用例子

 

 

    import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    import javax.swing.tree.*;

    public class JTreeDemo extends JFrame{
      static int i=0;
      DefaultMutableTreeNode root;
      /* DefaultMutableTreeNode是树数据结构中的通用节点 */
      DefaultMutableTreeNode child;
      DefaultMutableTreeNode chosen;
      JTree tree;
      DefaultTreeModel model; //使用 TreeNodes 的简单树数据模型.
     
      String[][] data={{"体育","足球","篮球","乒乓球"},{"娱乐","唱歌","跳舞","相声","小品"}, {"电视","长虹","海尔","创维"},{"戏剧","京剧","川剧","越剧"},{"国家","中国", "越南","朝鲜","德国"},{"武器","飞机","大炮","坦克"} };
     
      JTreeDemo(){
        Container contentPane=this.getContentPane();
        JPanel jPanel1=new JPanel(new BorderLayout());
        root=new DefaultMutableTreeNode("根");
        /* DefaultMutableTreeNode(Object userObject) 
           创建没有父节点和子节点、但允许有子节点的树节点,并使用指定的用户对象对它进行初始化。*/
     
        tree=new JTree(root); //建立以root为根的树
        jPanel1.add(new JScrollPane(tree),BorderLayout.CENTER);
        /* 将树添加至滚动窗格中,同时将滚动窗格添加进jPanel1面板 */
     
        model=(DefaultTreeModel)tree.getModel();
        /* TreeModel getModel() 
        返回正在提供数据的 TreeModel。 */
     
        JButton jButton1=new JButton("添加节点");

        jButton1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            if(i<data.length){
              child=new Branch(data[i++]).node();
              chosen=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
              /* Object getLastSelectedPathComponent() 
              返回当前选择的第一个节点中的最后一个路径组件。 */

              if(chosen==null){
                chosen=root;
              }
              model.insertNodeInto(child,chosen,0);
              /* void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) 
              对它进行调用,以便在父节点的子节点中的 index 位置插入 newChild。 */
            }
          }
        });

        jButton1.setBackground(Color.blue);
        jButton1.setForeground(Color.white);
        JPanel jPanel2=new JPanel();
        jPanel2.add(jButton1);
        jPanel1.add(jPanel2,BorderLayout.SOUTH);
        contentPane.add(jPanel1);
        this.setTitle("JtreeDemo");
        this.setSize(300,500);
        this.setLocation(400,400);
        this.setVisible(true);
      }

      class Branch{
        DefaultMutableTreeNode r;

        public Branch(String[] data){
          r=new DefaultMutableTreeNode(data[0]);
          for(int i=1;i<data.length;i++){
            r.add(new DefaultMutableTreeNode(data[i]));
          }
        }

        public DefaultMutableTreeNode node(){
          return r;
        }
      }

      public static void main(String args[]){
        JTreeDemo test=new JTreeDemo();
      }
    }

 

你可能感兴趣的:(数据结构,swing,体育)