java swing JFileChooser 锁定指定目录

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileSystemView;

class DirectoryRestrictedFileSystemView extends FileSystemView
{
    private final File[] rootDirectories;

    DirectoryRestrictedFileSystemView(File rootDirectory)
    {
        this.rootDirectories = new File[] {rootDirectory};
    }

    DirectoryRestrictedFileSystemView(File[] rootDirectories)
    {
        this.rootDirectories = rootDirectories;
    }

    @Override
    public File createNewFolder(File containingDir) throws IOException
    {       
        throw new UnsupportedOperationException("Unable to create directory");
    }

    @Override
    public File[] getRoots()
    {
        return rootDirectories;
    }

    @Override
    public boolean isRoot(File file)
    {
        for (File root : rootDirectories) {
            if (root.equals(file)) {
                return true;
            }
        }
        return false;
    }
}

public class Test {
	public static void main(String[] args ){
                //改变根路径
                FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("D:\\"));
		JFileChooser fileChooser = new JFileChooser(fsv);
                //指定初始路径
                fileChooser.setCurrentDirectory(new File("D:\\"));
		JFrame frame = new JFrame();
		frame.setSize(800, 600);
		frame.add(fileChooser);
		frame.setVisible(true);		
	}
}


通过继承 FileSystemView 这个类来改变系统根路径,然后设置初始路径,达到锁定效果。


你可能感兴趣的:(java,swing)