Java is not providing any option to remember last browsed directory. So we have to save the last browsed directory in global static variable of Util class and use that location at the time initiating new JFileChooser class.

Util Class Structure 

Here observe the code. We are saving parent folder of selected file or directory using setLastDir method and Returning the JFileChooser with last browsed directory path using getFileChooser method
public class Utils {
    private static String lastDir = null;

    public static JFileChooser getFileChooser() {
        if(lastDir != null) {
            JFileChooser fc = new JFileChooser(lastDir);
            return fc;
        } else {
            JFileChooser fc = new JFileChooser();
            return fc;
        }
    }

    public static void setLastDir(File file) {
        lastDir = file.getParent();
    }
}

Usage

Get JFileChooser from Utils class and send selected file to setLastDir method.
JFileChooser fc = Utils.getFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
     Utils.setLastDir(fc.getSelectedFile());
     ......
} else {
     System.out.println("Open command cancelled by user.");
}

1 comment:

  1. When the default Install from Internet option is chosen, setup.exe creates a local directory to store the packages before actually installing the contents. Near Me finds

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts