user3168279
user3168279

Reputation:

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 ;-)

Upvotes: 0

Views: 3459

Answers (2)

Goofyseeker311
Goofyseeker311

Reputation: 141

if you re-use the same JFileChooser, it will remember the last directory, where the file was selected. this can be for example achieved with following style of code.

public class MyClass extends JFrame {
   private JFileChooser filechooser = new JFileChooser();

   private void myfunction() {
      if (this.filechooser.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) {
         ... your code here ...
      }
   }
}

this behaviour is clearly documented in: https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Upvotes: 0

icza
icza

Reputation: 418605

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);

Upvotes: 2

Related Questions