jFilechooser显示文件夹

时间:2013-02-27 05:47:54

标签: java swing jfilechooser

我想在jfilechooser中显示当前目录的父文件夹 我想显示带有..的文件夹,该文件夹引用父文件夹

2 个答案:

答案 0 :(得分:3)

使用构造函数将文件路径作为参数,如下所示。

JFileChooser jfc = new JFileChooser(".\\..");

查看JFileChooser(File currentDirectory)

答案 1 :(得分:2)

这是“尝试”实现您请求的功能,我遇到的问题是它不可能完全复制系统正在做的事情。

基本上,目录组合框期望某种本地File对象(在Windows的情况下,sun.awt.shell.Win32ShellFolder2)。但似乎没有任何方法可以在提供的API中创建它们(并且您不希望手动创建它们,因为它会破坏外观和跨平台功能)。

enter image description here

import core.util.MethodInvoker;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import javax.swing.plaf.ComponentUI;

public class TestFileChooser {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(UIManager.getSystemLookAndFeelClassName());
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFileChooser fc = new JFileChooser(new MyFileSystemView());
                fc.showOpenDialog(null);

            }
        });
    }

    public static class MyFileSystemView extends FileSystemView {

        @Override
        public File[] getFiles(File dir, boolean useFileHiding) {
            File[] files = super.getFiles(dir, useFileHiding);

            List<File> fileList = new ArrayList<>(Arrays.asList(files));
            if (!isFileSystemRoot(dir)) {
                File newPath = FileSystemView.getFileSystemView().createFileObject(dir, "/..");
                fileList.add(0, newPath);
            }
            files = fileList.toArray(files);

            return files;
        }

        @Override
        public File createNewFolder(File containingDir) throws IOException {
            File newFolder = new File(containingDir + File.separator + "New Folder");
            if (!newFolder.mkdir()) {
                newFolder = null;
            }
            return newFolder;
        }
    }
}