就是只打开指定的目录下的文件夹(c:/files),不让选择其他的目录

解决方案 »

  1.   


    import java.io.File;import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    public class Test extends FileFilter {
    private JFileChooser jfc;

    public static String filePath = "C:" + System.getProperty("file.separator") + "test";//默认只能打开的跟路径
    public Test() {
    jfc = new JFileChooser();
    File file = new File(filePath);
    jfc.setCurrentDirectory(file);
    //jfc.setFileFilter(this);
    jfc.addChoosableFileFilter(this);
    jfc.showOpenDialog(null);
    }
    public static void main(String[] args) {
    System.out.println(filePath);
    new Test();
    }

    @Override
    public boolean accept(File f) {
    boolean flag = f.isDirectory() && f.getAbsolutePath().equals(Test.filePath);
    boolean flag2 = f.getAbsolutePath().startsWith(Test.filePath);
    if(flag | flag2)
    return true;
    else
    return false;
    }
    @Override
    public String getDescription() {
    return Test.filePath;
    }
    }这儿有一个,只能选择指定路径下的文件,可能不符合楼主的需求。
      

  2.   

    用 JFileChooser.setFileSelectionMode(DIRECTORIES_ONLY);具体如下:void javax.swing.JFileChooser.setFileSelectionMode(int mode)
    Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY.See Also:
    getFileSelectionMode
    Parameters:
    mode the type of files to be displayed: 
    JFileChooser.FILES_ONLY 
    JFileChooser.DIRECTORIES_ONLY 
    JFileChooser.FILES_AND_DIRECTORIES 
    Throws:
    IllegalArgumentException - if mode is an illegal file selection mode
    @beaninfo
    preferred: true bound: true description: Sets the types of files that the JFileChooser can choose. enum: FILES_ONLY JFileChooser.FILES_ONLY DIRECTORIES_ONLY JFileChooser.DIRECTORIES_ONLY FILES_AND_DIRECTORIES JFileChooser.FILES_AND_DIRECTORIES