Search code examples
javaswingjfilechooser

how to get a JFileChooser to remember a previous folder?


I'm trying to get the JFileChooser to remember the location of the previous location opened, and then next time open there, but is doesn't seem to remember. I have to open it twice: At the first run it works fine. But at the second run there's still the path locked from the first run. I have to open the JFileChooser dialog twice to get the newer path...

//Integrate ActionListener as anonymous class
this.openItem.addActionListener(new java.awt.event.ActionListener() {
    //Initialise actionPerformed 
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        //Generate choose file
        this.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = this.chooser.showOpenDialog(PDFcheck.this.openItem);
        if (this.theOutString != null){
        this.chooser.setCurrentDirectory(new File(this.theOutString)); }
        if(returnVal == JFileChooser.APPROVE_OPTION) {
        //theOutString = fc.getSelectedFile().getName();
        this.theOutString = this.chooser.getSelectedFile().getPath();
        System.out.println("You chose to open this file: " + this.theOutString);}
        }
        private String theOutString;
        private final JFileChooser chooser = new JFileChooser();
         });

thanks ;-)


Solution

  • Problem is that you first show the file chooser dialog, and you only set its current directory after that.

    You should first set the current directory first and then show the dialog:

    if (this.theOutString != null)
        this.chooser.setCurrentDirectory(new File(this.theOutString));
    int returnVal = this.chooser.showOpenDialog(PDFcheck.this.openItem);