Install JFileChooser to open the current directory

I created JFileChooser to open the file, but when I select the file and open it, the second time I want to select the file, JFileChooser is not in the current directory. How to install 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();} } 
+8
java file swing jfilechooser
source share
2 answers

Either pass the directory to the constructor using the File parameter (a File can also be a directory, FYI), or use .setCurrentDirectory(File dir) before making JFileChooser visible.

In addition, in order for JFileChooser to remain in the same folder, you need to save the folder with the file / directory selected for the last time and use the THAT value to manage the folder that it launches at subsequent times through .setCurrentDirectory(File dir)

+12
source share

Make the selector an attribute of the class level and create it only once. Thus, it not only indicates where it was closed, but will have the same size, location, file filter, etc.

+3
source share

All Articles