大家都知道QQ吧,QQ的好友列表是用树来实现的吧,
可是:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
JTree jt = new JTree(root);
root.add(new ...);
root.add(new ...);
问题是,怎么让根节点root 不显示,而只是显示叶节点。类似于QQ的平级结构
在线等。。。。setRootVisible(false); 但是必须将asksAllowsChildren设为true;
再加上下面的代码就可以了
使用方法: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);
}
}