日期:2014-05-20 浏览次数:20762 次
package exercise; import java.io.File; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class Jtree extends JFrame { private JScrollPane jsp; private JTree jtr; private static DefaultMutableTreeNode root; public Jtree() { setBounds(50, 50, 500, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); File file=new File("d:\\1"); root=new DefaultMutableTreeNode(file); search(file, root); init(); //最后创建JTree } public void init() { jtr=new JTree(root); jsp=new JScrollPane(jtr); add(jsp); } public static void search(File file,DefaultMutableTreeNode node) { File[] f=file.listFiles(); for(int i=0;i<f.length;i++) { DefaultMutableTreeNode nodes=new DefaultMutableTreeNode(f[i].getName()); node.add(nodes); if(f[i].isDirectory()) { search(f[i],nodes); } } } public static void main(String[] args) { new Jtree().setVisible(true); } }
------解决方案--------------------
import java.io.File; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class Jtree extends JFrame { private JScrollPane jsp; private JTree jtr; private static DefaultMutableTreeNode root; public Jtree() { setBounds(50, 50, 500, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); File file = new File("D:\\"); File[] fs = file.listFiles(); System.out.println(fs.length); root = new DefaultMutableTreeNode(file); init(); search(file, root); this.setVisible(true); } public void init() { jtr = new JTree(root); jsp = new JScrollPane(jtr); add(jtr); } public static void search(File file, DefaultMutableTreeNode node) { File[] f = file.listFiles(); for (int i = 0; i < f.length; i++){ DefaultMutableTreeNode nodes = new DefaultMutableTreeNode( f[i].getName()); node.add(nodes); if (f[i].isDirectory()) { search(f[i], nodes); } else{//just here。加上这个没问题。。 return; } } } public static void main(String args[]){ new Jtree(); } }