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