Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

java - JFileChooser, want to lock it to one directory

I have this program where u can download files and i want the JFileChooser to be locked to one folder(directory) so that the user cant browse anything else. He can only choose files from for example the folder, "C:UsersThomasDropboxProsjekt RMISERVER". I have tried so search but did not find anything. The code I have is:

String getProperty = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Prosjekt RMI/SERVER/"); //opens in the directory "//C:/Users/Thomas/Dropbox/Project RMI/SERVER/"
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());

And this is working fine, but now i can go to the folder Project RMI, that i don't want it to do.

Thanks in Advance :)

Edit: What I did with your help:

JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Project RMI/SERVER/"); 
                chooser.setFileView(new FileView() {
                    @Override
                    public Boolean isTraversable(File f) {
                        return (f.isDirectory() && f.getName().equals("SERVER")); 
                    }
                });
                int returnVal = chooser.showOpenDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    System.out.println("You chose to open this file: "
                            + chooser.getSelectedFile().getName());
                }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set a FileView and override the isTraversable method so that it returns true only for the directory you want the user to see.

Here is an example:

String getProperty = System.getProperty("user.home");
final File dirToLock = new File(getProperty + "/Dropbox/Prosjekt RMI/SERVER/");
JFileChooser fc = new JFileChooser(dirToLock);
fc.setFileView(new FileView() {
    @Override
    public Boolean isTraversable(File f) {
         return dirToLock.equals(f);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...