?
?
实现附件中图片的效果的java代码:
?
package test; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; /** * 名称:JTree的写法 * 作者: yue1132 * 版本:0.0.1 * 日期:2012-06-29 */ public class JTreeTest extends JPanel{ private JTree cityTree; /** * @param args */ public JTreeTest(){ this.addcityTree(); } private void addcityTree() { // TODO Auto-generated method stub this.cityTree = new JTree(); //设置根节点 DefaultMutableTreeNode root = new DefaultMutableTreeNode("四川省"); //设置一级节点 DefaultMutableTreeNode city1 = new DefaultMutableTreeNode("成都市"); DefaultMutableTreeNode city2 = new DefaultMutableTreeNode("绵阳市"); DefaultMutableTreeNode city3 = new DefaultMutableTreeNode("乐山市"); //设置二级目录,并把二级节点绑定到一级节点 city1.add(new DefaultMutableTreeNode("成都市外国语学校")); city1.add(new DefaultMutableTreeNode("成都十二中")); city1.add(new DefaultMutableTreeNode("成都七中")); city2.add(new DefaultMutableTreeNode("南山中学")); city2.add(new DefaultMutableTreeNode("绵阳中学")); city2.add(new DefaultMutableTreeNode("绵阳三中")); city3.add(new DefaultMutableTreeNode("乐山外国语学校")); city3.add(new DefaultMutableTreeNode("乐山二中")); //把一级目录绑定到根节点 root.add(city1); root.add(city2); root.add(city3); DefaultTreeModel model= new DefaultTreeModel(root); this.cityTree.setBounds(0, 0, 200, 450); this.cityTree.setModel(model); for (int i = 0; i < cityTree.getRowCount(); i++) cityTree.expandRow(i); this.add(cityTree); //JTree添加选择监听器 cityTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { // TODO Auto-generated method stub DefaultMutableTreeNode select = (DefaultMutableTreeNode)e.getPath().getLastPathComponent(); //如果当前选中一个节点,则弹出一个对话框并显示节点上的文本内容 if(select.toString()!=null){ JOptionPane.showMessageDialog(null, select.toString()); } } }); } //添加一个Frame测试新建的cityTree public static void main(String[] args) { // TODO Auto-generated method stub JFrame frame =new JFrame(); frame.getContentPane().setLayout(null); frame.setDefaultCloseOperation(3); frame.setSize(800, 600); JTreeTest tree = new JTreeTest(); tree.setLayout(null); tree.setBounds(10, 10, 200, 500); frame.getContentPane().add(tree);//把tree面板添加到JFrame中 frame.setLocationRelativeTo(null);//设置JFrame居中对齐 frame.setVisible(true);//设置JFrame可见 } }