Как использовать JTree для отображения файлов из каталога в JPanel?

Я работаю над разработкой графического интерфейса с использованием Swing. Графический интерфейс реализован таким образом, что когда пользователь хочет загрузить набор текстовых файлов, должно открыться диалоговое окно выбора файлов, и пользователь выбирает каталог, в котором присутствуют все файлы. Теперь я хочу перечислить все файлы в выбранном каталоге в JScrollPane с помощью JTree. Я использую этот пример для реализации JTree в своем коде: http://www.java2s.com/Code/Java/File-Input-Output/FileTreeDemo.htm

Однако JTree не отображается в JPanel после выбора каталога. Я поместил код JTree в метод actionPerformed(). Я не уверен, что это правильный путь.

Вот код:

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

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) {}
}

После повторной проверки контейнера содержимого графический интерфейс выглядит следующим образом:

введите здесь описание изображения


person novicegeek    schedule 30.07.2015    source источник


Ответы (1)


Вы не прошли повторную проверку содержащего content контейнера. В конце вашего метода actionPerformed добавьте строки

//content.invalidate();
content.revalidate();
content.repaint();
person ControlAltDel    schedule 30.07.2015
comment
Да, это сработало так, как я хотел. Однако для отображения я получаю отдельное поле с полосами прокрутки внутри спектральных файлов JPanel, и оно меньше. Размеры JPanel и JScrollPane одинаковы в коде. Я обновил вопрос о том, как выглядит графический интерфейс. - person novicegeek; 30.07.2015
comment
Мне удалось добиться желаемых результатов. - person novicegeek; 30.07.2015