Java 仅从此文件夹中选择FileChooser getAttachement

Java 仅从此文件夹中选择FileChooser getAttachement,java,swing,jfilechooser,Java,Swing,Jfilechooser,如何使用户仅从指定文件夹中选择文件 int returnVal = fc.showOpenDialog(FileChooser.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); source = file.getAbsolutePath(); fileName = file.getName(); attachText.setText(f

如何使用户仅从指定文件夹中选择文件

int returnVal = fc.showOpenDialog(FileChooser.this);

if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    source = file.getAbsolutePath();
    fileName = file.getName();
    attachText.setText(fileName);
    source = source.replace("\\","\\\\");                
}

在这里,我将从任何文件夹中获取该文件,其中我只希望文件来自G:\Project\Attachments。如何执行此操作?

您可以在构造函数中传递目录:

JFileChooser filechooser = new JFileChooser(theDirectory);
还是定下来

filechooser.setCurrentDirectory(theDirectory);
在您的案例中,目录是:

File theDirectory = new File("G:\\Project\\Attachments");

FileChooser.this
这是什么?@vijay这将允许用户走出目录并选择其他文件。+1,尽管SingleRootFileSystemView不是标准类。也许你指的是在
File dir = new File("G:\\Project\\Attachments");
FileSystemView fsv = new SingleRootFileSystemView(dir);
JFileChooser fileChooser = new JFileChooser(fsv);
int returnVal = fc.showOpenDialog(fileChooser);

if (returnVal == JFileChooser.APPROVE_OPTION) {