如何使用JTree显示JPanel目录中的文件? [英] How to use JTree to display files from a directory in JPanel?

查看:123
本文介绍了如何使用JTree显示JPanel目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swing开发GUI。 GUI以这样的方式实现:当用户想要加载一组文本文件时,然后应该打开文件选择器对话框并且用户选择存在所有文件的目录。现在,我想使用JTree将所选目录中的所有文件列入JScrollPane。我正在使用此示例在我的代码中实现JTree:

解决方案

您尚未重新验证包含内容容器。在actionPerformed方法的最后,添加行

  // content.invalidate(); 
content.revalidate();
content.repaint();


I am working on developing a GUI using Swing. The GUI is implemented in such a way that the when the user wants to load a set of text files, then the filechooser dialog should open and the user selects the directory in which all the files are present. Now, I want to list all the files in the selected directory into a JScrollPane using JTree. I am using this example to implement JTree in my code: http://www.java2s.com/Code/Java/File-Input-Output/FileTreeDemo.htm

However, the JTree is not displayed in the JPanel after I select the directory. I have placed the JTree code in the actionPerformed() method. I am not sure if this is the right way.

Here is the code:

public void actionPerformed(ActionEvent e) {

        //Handle open button action.
        if (e.getSource() == OpenFileButton) {
            int returnVal = fc.showOpenDialog(GUIMain.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
                System.out.println(file);
                File[] filesInDirectory = file.listFiles();

                SortFile sf = new SortFile();

                // Calls sortByNumber method in class SortFile to list the files number wise
                filesInDirectory = sf.sortByNumber(filesInDirectory);

                FileTreeModel model = new FileTreeModel(file);
                tree = new JTree();
                tree.setModel(model);    
                spectralFilesScrollPane = new JScrollPane(tree);
                //  add(BorderLayout.CENTER, spectralFilesScrollPane);
                spectralFilesScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                spectralFilesScrollPane.setPreferredSize(new Dimension(250, 145));
                spectralFilesScrollPane.setMinimumSize(new Dimension(10, 10));
                spectralFilesScrollPane.setBorder(
                        BorderFactory.createCompoundBorder(
                                BorderFactory.createTitledBorder("Spectral Files"),
                                BorderFactory.createEmptyBorder(5, 5, 5, 5)));

                content.add(spectralFilesScrollPane);
                spectralFilesScrollPane.setVisible(true);
            }
        }
    }

FileTreeModel.java class

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.io.File;

/**
 * The methods in this class allow the JTree component to traverse
 * the file system tree, and display the files and directories.
 **/
class FileTreeModel implements TreeModel {

    // We specify the root directory when we create the model.
    protected File root;
    public FileTreeModel(File root) {
        System.out.println("I am in FileTree Model");
        this.root = root; }

    // The model knows how to return the root object of the tree
    public Object getRoot() { return root; }

    // Tell JTree whether an object in the tree is a leaf or not
    public boolean isLeaf(Object node) {  return ((File)node).isFile(); }

    // Tell JTree how many children a node has
    public int getChildCount(Object parent) {
        String[] children = ((File)parent).list();
        if (children == null) return 0;
        System.out.println("printing child length:" + children.length);
        return children.length;
    }

    // Fetch any numbered child of a node for the JTree.
    // Our model returns File objects for all nodes in the tree.  The
    // JTree displays these by calling the File.toString() method.
    public Object getChild(Object parent, int index) {
        String[] children = ((File)parent).list();
        if ((children == null) || (index >= children.length)) return null;
        return new File((File) parent, children[index]);
    }

    // Figure out a child's position in its parent node.
    public int getIndexOfChild(Object parent, Object child) {
        String[] children = ((File)parent).list();
        if (children == null) return -1;
        String childname = ((File)child).getName();
        for(int i = 0; i < children.length; i++) {
            if (childname.equals(children[i])) return i;
        }
        return -1;
    }

    // This method is only invoked by the JTree for editable trees.
    // This TreeModel does not allow editing, so we do not implement
    // this method.  The JTree editable property is false by default.
    public void valueForPathChanged(TreePath path, Object newvalue) {}

    // Since this is not an editable tree model, we never fire any events,
    // so we don't actually have to keep track of interested listeners.
    public void addTreeModelListener(TreeModelListener l) {}
    public void removeTreeModelListener(TreeModelListener l) {}
}

After revalidating the content container, the GUI looks like this:

解决方案

You haven't revalidated the containing content Container. At the end of your actionPerformed method, add the lines

//content.invalidate();
content.revalidate();
content.repaint();

这篇关于如何使用JTree显示JPanel目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆