Java JTree_4

Java JTree_4

package com.han;

import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class JTree_4 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2323546046067757781L;

	public JTree_4() {
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT");
		DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("人事管理");
		DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("待遇管理");
		DefaultMutableTreeNode nodeC = new DefaultMutableTreeNode("系统维护");
		root.add(nodeA);
		root.add(nodeB);
		root.add(nodeC);
		DefaultMutableTreeNode nodeAA = new DefaultMutableTreeNode("帐套管理");
		DefaultMutableTreeNode nodeAB = new DefaultMutableTreeNode("考勤管理");
		DefaultMutableTreeNode nodeAC = new DefaultMutableTreeNode("奖惩管理");
		DefaultMutableTreeNode nodeAD = new DefaultMutableTreeNode("培训管理");
		nodeA.add(nodeAA);
		nodeA.add(nodeAB);
		nodeA.add(nodeAC);
		nodeA.add(nodeAD);
		DefaultMutableTreeNode nodeBA = new DefaultMutableTreeNode("帐套管理");
		DefaultMutableTreeNode nodeBB = new DefaultMutableTreeNode("人员设置");
		DefaultMutableTreeNode nodeBC = new DefaultMutableTreeNode("待遇报表");
		nodeB.add(nodeBA);
		nodeB.add(nodeBB);
		nodeB.add(nodeBC);
		DefaultMutableTreeNode nodeCA = new DefaultMutableTreeNode("企业架构");
		DefaultMutableTreeNode nodeCB = new DefaultMutableTreeNode("基本资料");
		DefaultMutableTreeNode nodeCC = new DefaultMutableTreeNode("系统初始化");
		nodeC.add(nodeCA);
		nodeC.add(nodeCB);
		nodeC.add(nodeCC);
		
		DefaultTreeModel defaultTreeModel = new DefaultTreeModel(root);
		JTree tree = new JTree(defaultTreeModel);
		getContentPane().add(tree, BorderLayout.WEST);
		
		// expand initially all nodes of the tree
		@SuppressWarnings("rawtypes")
		Enumeration enumerate = root.preorderEnumeration();
		while (enumerate.hasMoreElements()) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerate.nextElement();
			tree.expandPath(new TreePath(node.getPath()));
		}
		
		// set root node invisible
		tree.setRootVisible(false);
		
		// set nodes' icons
		DefaultTreeCellRenderer treeCellRenderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
		treeCellRenderer.setLeafIcon(null);
		treeCellRenderer.setClosedIcon(null);
		treeCellRenderer.setOpenIcon(null);
		
		// set the connection line way
		tree.putClientProperty("JTree.lineStyle", "None");
		
		// set row height of the tree and font style of the node object 
		tree.setRowHeight(20);
		tree.setFont(new Font("宋体", Font.BOLD, 14));
	}
	
	public static void main(String[] args) {
		JTree_4 instance = new JTree_4();
		instance.setTitle("定制树");
		instance.setVisible(true);
		instance.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		instance.pack();
	}
}


你可能感兴趣的:(JTree)