如何让JTree对象生成之后自动处于展开状态啊?????

解决方案 »

  1.   

    SWT里面有一个方法,Swing中应该也有,你查一下API,我现在记得不是很清楚。
      

  2.   

    写个方法,让它自动展开import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.*;
     
    public class Test {
        public static void expandAll(JTree tree, TreePath path) {
            //assert (tree != null) && (path != null);
            tree.expandPath(path);
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration i = node.children(); i.hasMoreElements(); ) {
                expandAll(tree, path.pathByAddingChild(i.nextElement()));
            }
        }
             
        public static void main(String[] args) {
            JFrame f = new JFrame();
            JTree tree = new JTree();        
            expandAll(tree, new TreePath(tree.getModel().getRoot())); // do more check to make sure no NullPointerException ...
            f.setContentPane(new JScrollPane(tree));
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    }