JTree单击事件

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.FlowLayout;
import java.awt.GridLayout;
public class TreeDemo extends JFrame{
 JTree jTree=new JTree();
 JTextField jTextField =new JTextField();
 GridLayout lay=new GridLayout(1,1);
 public TreeDemo(){
  treeinit();
  this.setSize(400,400);
  this.setLayout(lay);
  this.add(jTree);
  this.add(jTextField);
  this.setVisible(true);
  jTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreeValueChanged(evt);
            }
        });
 }
  private void jTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {
        DefaultMutableTreeNode selectedNode=(DefaultMutableTreeNode) jTree.getLastSelectedPathComponent();//返回最后选定的节点
        if(selectedNode.toString().equals("child")){
         jTextField.setText("I LOVE YOU");
        }

}
 public void treeinit(){
  DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
  DefaultMutableTreeNode father=new DefaultMutableTreeNode("father");
        DefaultMutableTreeNode child=new DefaultMutableTreeNode("child");
        father.add(child);
        root.add(father);
        TreeModel treeModel = new DefaultTreeModel(root);
        jTree.setModel(treeModel);
 }
 public static void main(String args[]){
  new TreeDemo();
 }
}

  

posted @ 2017-01-11 11:47  削肾客  阅读(3512)  评论(0编辑  收藏  举报