Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set the JFileChooser to open current directory

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();}
             } 
like image 677
Tofiq Avatar asked Oct 15 '11 21:10

Tofiq


2 Answers

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)

like image 54
jefflunt Avatar answered Oct 14 '22 11:10

jefflunt


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.

like image 42
Andrew Thompson Avatar answered Oct 14 '22 11:10

Andrew Thompson