简体   繁体   中英

How to set the last path as the next default using JFileChooser

I have several dialog boxes which provide a File Chooser. For the first, my coding was like this

JFileChooser chooser= new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal= chooser.showOpenDialog(this);

        if(returnVal==JFileChooser.APPROVE_OPTION){
            File f= chooser.getSelectedFile();
            jTextField1.setText(f.getPath());
            chooser.setCurrentDirectory(f);
        }

In my case, i would like to set the last path which is selected as the default path in next selection JFileChooser. Is there any solution for me? Thanks for any response

You will have to "remember" the last path.

This can easily be done by storing the value in a instance variable...

private File lastPath;
//...
lastPath = f.getParentFile();

And simply resetting it when you need to...

//...
if (lastPath != null) {
    chooser.setCurrentDirectory(lastPath);
}

You could also use a single instance of the JFileChooser , so each time you show it, it will be at the last location it was used...

Depending on your requirements, you can use Preferences to store it away and use it again after the program has been restarted.

 Preferences pref = Preferences.userRoot();

// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));

int returnVal = chooser.showOpenDialog(null);

if (returnVal == JFileChooser.APPROVE_OPTION)
{
    File f = chooser.getSelectedFile();
    chooser.setCurrentDirectory(f);

    // Save the selected path
    pref.put("DEFAULT_PATH", f.getAbsolutePath());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM