set the JFileChooser to open current directory
Asked Answered
Z

2

8

I created a JFileChooser to open a file, but when I select a file and open it,for second the time that i want to select a file, the JFileChooser is not in the current directory. How set the JFileChooser to open the current directory?

JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
         fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
         int result = fileChooser.showOpenDialog( this );
         if ( result == JFileChooser.APPROVE_OPTION ){
              File fileName = fileChooser.getSelectedFile();
              File path=fileChooser.getCurrentDirectory();
              if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
              {
                 JOptionPane.showMessageDialog( this, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE );
              }
              else{
               currentPath=path.getPath()+"\\"+fileName.getName();}
             } 
Zoraidazorana answered 15/10, 2011 at 21:53 Comment(0)
W
12

Either pass the directory into the constructor via the File parameter (a File can also be a directory, FYI), or use the .setCurrentDirectory(File dir) method before you make the JFileChooser visible.

Also, to make the JFileChooser stay in the same folder, you need to save the folder of the file/directory chosen from last time, and use THAT value to control which folder it starts in the subsequent times via .setCurrentDirectory(File dir)

Whispering answered 15/10, 2011 at 21:57 Comment(0)
G
3

Make the chooser a class level attribute and create it only once. That way, it not only points to where it did when closed, but will have the same size, location, file filter selected etc.

Gillie answered 16/10, 2011 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.