日期:2014-05-20 浏览次数:21018 次
//中忙你写了个,看看吧 import java.awt.Color; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; public class TestJTree implements TreeSelectionListener { JTree tree; DefaultMutableTreeNode root; DefaultTreeModel model; JSplitPane mainSplitpane; public TestJTree() { mainSplitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // 分割面板 model = new DefaultTreeModel(root); // 设置树的缺省模式 tree = new JTree(model); root = new DefaultMutableTreeNode("TestTree");//树根 DefaultMutableTreeNode level1 = new DefaultMutableTreeNode("A"); DefaultMutableTreeNode level2 = new DefaultMutableTreeNode("分支1"); // 树叶 DefaultMutableTreeNode level3 = new DefaultMutableTreeNode("分支2"); level1.add(level2); level1.add(level3); root.add(level1); tree = new JTree(root); DefaultTreeCellRenderer render = new DefaultTreeCellRenderer(); // 树叶 render.setTextSelectionColor(Color.blue); // 选择时候的颜色 render.setTextNonSelectionColor(Color.black); // 非选择时候颜色 tree.setCellRenderer(render); tree.addTreeSelectionListener(this); JPanel firstimg = new JPanel(); firstimg.setLayout(null); ImageIcon img = new ImageIcon("img/firstimg.jpg"); JLabel imgLabel = new JLabel(img); // 面板,此处实际是一张图片 imgLabel.setBounds(0, 0, img.getIconWidth(), img .getIconHeight()); firstimg.add(imgLabel); mainSplitpane.setDividerLocation(185); mainSplitpane.setLeftComponent(tree); mainSplitpane.setRightComponent(firstimg); JFrame jf = new JFrame("TestTree"); jf.setSize(900, 600); jf.setContentPane(mainSplitpane); jf.setLocationRelativeTo(null); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void valueChanged(TreeSelectionEvent e) { if (e.getSource() == tree) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree .getLastSelectedPathComponent(); if (node.isLeaf()) { System.out.println(node.toString()); TreePath visiblePath = new TreePath(model.getPathToRoot(node)); System.out.println(visiblePath.toString()); if (node.toString().equals("分支1")) { //mainSplitpane.setRightComponent(...do what you want here...); 重点在这里 } } } } public static void main(String[] args) { new TestJTree(); } }