更新JTree文件目录

时间:2017-03-10 00:49:10

标签: java swing jtree

如何进行编辑,以便GUI反映用户何时创建目录或文件?我尝试过关注其他帖子的建议,但没有任何工作......该程序本质上是一个MySQL工作台模拟器,因此当用户键入类似" CREATE TABLE db.tb;"它应该创建表,然后更新JTree显示。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.File;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;


public class DatabasePanel extends JPanel{
    JTree tree;
    DefaultMutableTreeNode root;
    DefaultTreeModel model;
    public DatabasePanel() {
        setTree();
    }

    public void setTree() {
        root = new DefaultMutableTreeNode("root", true);
        model = new DefaultTreeModel(root);
        getList(root, new File(System.getProperty("user.dir")));
        tree = new JTree(model);
        tree.setRootVisible(false);
        tree.setEditable(true);
        tree.setShowsRootHandles(true);
        JScrollPane scp = new JScrollPane(tree);
        scp.setPreferredSize(new Dimension(200,500));
        add(scp, "Center");
    }

    public void getList(DefaultMutableTreeNode node, File f) {
        try {
            if (!f.isDirectory()) {
                if (!f.getName().startsWith(".")) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode(f.getName());
                    model.insertNodeInto(child, node, 0);
                    revalidate();
                    ((DefaultTreeModel)tree.getModel()).reload();
                }
            } else if (f.isDirectory() && !f.getName().startsWith(".")){
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(f.getName());
                model.insertNodeInto(child, node, 0);

                File fList[] = f.listFiles();
                for (int i = 0; i < fList.length; i++) {
                        if (!f.getName().startsWith(".")) {
                            getList(child, fList[i]);
                        }
                }
            }
        } catch (Exception e) {
            return;
        }
    }

}

0 个答案:

没有答案