/**
* 树控件使用
* @author lgh
*/
public class JTreeTest extends JFrame {
public JTreeTest() {
init();
}
private void init() {
this.setSize(800, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.add(createJTree(), BorderLayout.CENTER);
this.setVisible(true);
}
/**
* 创建一个树
* @return
*/
private JScrollPane createJTree() {
DefaultMutableTreeNode node = new DefaultMutableTreeNode();
node.setUserObject(new MyTreeNode(new ImageIcon(Pic.tree2), "root"));
JTree jt = new JTree(node);
jt.setCellRenderer(new MyTreeCellRenderer());
createRootMutableTreeNode(node);
JScrollPane jsp = new JScrollPane(jt);
return jsp;
}
private void createRootMutableTreeNode(DefaultMutableTreeNode root) {
root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node1")));
root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node2")));
root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node3")));
root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node4")));
root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node5")));
}
public static void main(String[] args) {
JTreeTest jTreeTest = new JTreeTest();
}
private class MyTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
MyTreeNode jtreeNode = (MyTreeNode) node.getUserObject();
this.setIcon(jtreeNode.getIcon());
this.setText(jtreeNode.getName());
this.setOpaque(true);
if (selected) {
this.setBackground(new Color(178, 180, 191));
} else {
this.setBackground(new Color(255, 255, 255));
}
return this;
}
}
private class MyTreeNode extends DefaultMutableTreeNode {
private Icon icon;
private String name;
public MyTreeNode(Icon icon, String name) {
this.icon = icon;
this.name = name;
}
public MyTreeNode() {
super();
}
/**
* @return the icon
*/
public Icon getIcon() {
return icon;
}
/**
* @param icon the icon to set
*/
public void setIcon(Icon icon) {
this.icon = icon;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
}