import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
public class TreeDemo extends JFrame {
JTree jTree = new JTree();
JLabel jLabel = new JLabel();
GridLayout lay = new GridLayout(1, 1);
//设置输出面板的属性
public TreeDemo() {
treeinit();
this.setSize(400, 400);
this.setLayout(lay);
this.add(jTree);
this.add(jLabel);
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 != null ) {
//将节点名称添加到jLabel中
jLabel.setText(selectedNode.toString());
}
}
//初始化树结构
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[]) {
//运行TreeDemo
new TreeDemo();
}
}
添加就可以显示,不需要repaint。。。。。