package ch01.section1.ex;
import java.awt.BorderLayout;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
public class TreeImage extends JFrame{
/**
* javax.swing.tree.DefaultMutableTreeNode是定义树的节点(包括子节点)
* javax.swing.tree.DefaultMutableTreeNode.add(子节点)
*/
DefaultMutableTreeNode root=new DefaultMutableTreeNode("根节点");
DefaultMutableTreeNode node1=new DefaultMutableTreeNode("一级节点一");
JTextField textf;
public TreeImage() throws HeadlessException {
node1.add(new DefaultMutableTreeNode("二级节点一"));
DefaultMutableTreeNode node21=new DefaultMutableTreeNode("二级节点二");
node21.add(new DefaultMutableTreeNode("二级节点二一"));
node21.add(new DefaultMutableTreeNode("二级节点二二"));
node21.add(new DefaultMutableTreeNode("二级节点二三"));
node1.add(node21);
root.add(node1);
root.add(new DefaultMutableTreeNode("一级节点二"));
root.add(new DefaultMutableTreeNode("一级节点三"));
root.add(new DefaultMutableTreeNode("一级节点四"));
/**
* 要将节点存入树中
* javax.swing.tree.DefaultTreeCellRenderer是定义树形状的类
* javax.swing.tree.DefaultTreeCellRenderer.setLeafIncon(null)//默认是系统的文件图标
*/
JTree tree=new JTree(root);
DefaultTreeCellRenderer render=(DefaultTreeCellRenderer)tree.getCellRenderer();
render.setLeafIcon(null);
render.setOpenIcon(null);
render.setClosedIcon(null);
/**
* 点击节点,操作相关事件
*/
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent e) {
TreePath tp=e.getPath();//获得根路径
String info=tp.getLastPathComponent().toString();//获得最后节点的路径名称
textf.setText(info);//这里是显示在文框中
}});
//注意在new JScrollPane时,一定要将组间在new时就初始话,后面add(组间),不显示
JScrollPane jsp=new JScrollPane(tree);
textf=new JTextField();
textf.setEditable(false);
this.add(jsp,BorderLayout.CENTER);
getContentPane().add(textf,BorderLayout.SOUTH);
setSize(250,200); //设置窗口尺寸
setVisible(true); //设置窗口可视
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
}
public static void main(String[] args) {
new TreeImage();
}
}
树结构的实现
最新推荐文章于 2024-07-05 18:34:12 发布