JAVA實現檔案樹

來源:互聯網
上載者:User

你想你的Swing程式擁有像資源管理員一樣的樹嗎?還要Lazy loading的嗎?

那就看看我下面實現的檔案樹代碼

public class ExplorerTree extends JPanel {<br /> private JTree tree;<br /> private TreePath treePath;</p><p> public ExplorerTree() {<br /> this.setLayout(new BorderLayout());<br /> DefaultMutableTreeNode root = new DefaultMutableTreeNode("Explorer");<br /> tree = new JTree(root);<br /> File[] roots = File.listRoots();<br /> for (int i = 0; i < roots.length; i++) {<br /> DefaultMutableTreeNode node = new DefaultMutableTreeNode(roots[i].getPath());<br /> root.add(node);<br /> }<br /> MouseListener ml = new MouseAdapter() {<br /> public void mousePressed(MouseEvent e) {<br /> try {<br /> TreePath tp = tree.getPathForLocation(e.getX(), e.getY());<br /> if (tp != null) {<br /> treePath = tp;<br /> int size = treePath.getPath().length;<br /> StringBuffer pathname = new StringBuffer();<br /> if (size > 0) {<br /> for (int i = 1; i < size; i++) {<br /> if (i > 2) {<br /> pathname.append("//");<br /> }<br /> pathname.append(treePath.getPath()[i].toString());</p><p> }<br /> System.out.println(pathname.toString());<br /> File file = new File(pathname.toString());<br /> File[] list = file.listFiles();<br /> for (int i = 0; i < list.length; i++) {<br /> String[] strings = list[i].getPath().split("////");<br /> DefaultMutableTreeNode node = new DefaultMutableTreeNode(strings[strings.length - 1]);<br /> ((DefaultMutableTreeNode) tp.getLastPathComponent()).add(node);<br /> }<br /> }<br /> }<br /> } catch (Exception e1) {<br /> System.out.println("can not open");<br /> }<br /> }<br /> };<br /> tree.addMouseListener(ml);<br /> tree.setShowsRootHandles(true);<br /> tree.setRootVisible(true);<br /> JScrollPane scrPane = new JScrollPane(tree);<br /> add(scrPane);<br /> }</p><p> public static void main(String[] args) {<br /> JFrame jFrame = new JFrame("Explorer");<br /> jFrame.setLayout(new BorderLayout());<br /> jFrame.add(new ExplorerTree());<br /> jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br /> jFrame.setSize(300, 700);<br /> jFrame.setVisible(true);<br /> }<br />}

最近比較忙,沒時間寫blog,就拿些代碼來獻獻醜了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.