java 树的讨论
大家都知道QQ吧,QQ的好友列表是用树来实现的吧,
可是:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
JTree jt = new JTree(root);
root.add(new ...);
root.add(new ...);
使用方法:SwingUtil.expandTree(tree);
public class SwingUtil {
public static void expandTree(JTree tree) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
expandTree(tree, new TreePath(root));
}
public static void expandTree(JTree tree, TreePath path) {
TreeNode node = (TreeNode) path.getLastPathComponent();
// Go to leaf
if (node.getChildCount() > 0) {
Enumeration<TreeNode> children = node.children();
while (children.hasMoreElements()) {
TreeNode n = children.nextElement();
TreePath newPath = path.pathByAddingChild(n);
expandTree(tree, newPath);
}
}
tree.expandPath(path);
}
}