package com.EditJTree;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
//java tree自动展开树
public class JTreeTest extends JFrame {
//增加带滚动条容器
JScrollPane jScrollPane1 = new JScrollPane();
//创建树对象
JTree treeObj = new JTree();
public JTreeTest () {
try {
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
private void jbInit() throws Exception {
getContentPane().setLayout(null);
setSize(new Dimension(434, 347));
setTitle("JTree Test");
jScrollPane1.setBounds(new Rectangle(9, 9, 429, 317));
this.getContentPane().add(jScrollPane1);
expandTree(treeObj);
jScrollPane1.getViewport().add(treeObj);
setVisible(true);
}
/**完全展开一个JTree
* @param tree JTree
*/
public static void expandTree(JTree tree) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
expandAll(tree, new TreePath(root), true);
}
/**
* 完全展开或关闭一个树,用于递规执行
* @param tree JTree
* @param parent 父节点
* @param expand 为true则表示展开树,否则为关闭整棵树
*/
private static void expandAll(JTree tree, TreePath parent, boolean expand) {
//Traverse children
TreeNode node = (TreeNode) parent.
getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements(); ) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
expandAll(tree, path, expand);
}
}
if (expand) {
tree.expandPath(parent);
} else {
tree.collapsePath(parent);
}
}
public static void main(String[] args) {
JTreeTest dJTreeTest = new JTreeTest();
}
}