JAVA SWING JTREE

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class JTreeDemo {
 JFrame jframe;
 JTree tree;

 public JTreeDemo() {
  initGUI();
 }

 public void initGUI() {
  jframe = new JFrame("JTree DEMO");
  jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  tree = new JTree();
  // 设置单选模式
  tree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION);
  jframe.getContentPane().add(tree);
  jframe.pack();
  jframe.setVisible(true);
  tree.addTreeSelectionListener(new TreeSelectionListener() {

   public void valueChanged(TreeSelectionEvent e) {
    // 返回最后选中的结点
    DefaultMutableTreeNode note = (DefaultMutableTreeNode) tree
      .getLastSelectedPathComponent();
    if (note.isLeaf()) {
     // 获得这个结点的名称
     String name = note.toString();
     DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) note
       .getParent();
     System.out.println(parentNode.getUserObject().toString()
       + "," + name);
    }
   }

  });
 }

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

你可能感兴趣的:(JAVA SWING JTREE)