[ACCEPTED]-jfilechooser - set directory to a path in a file-jfilechooser

Accepted answer
Score: 22

Try to pass the current directory directly 1 in the constructor:

filechooser = new JFileChooser(theDirectory);
Score: 6

If you consult the API, using the default constructor 17 (i.e. new JFileChooser()):

Constructs a JFileChooser pointing 16 to the user's default directory. This default 15 depends on the operating system. It is 14 typically the "My Documents" folder 13 on Windows, and the user's home directory 12 on Unix.

This would seem to account for always 11 opening to My Documents, but this isn't your problem. In 10 fact, your problem lies with setting the current directory (i.e. setCurrentDirectory(theDirectory)):

Sets 9 the current directory. Passing in null 8 sets the file chooser to point to the 7 user's default directory. This default 6 depends on the operating system. It is 5 typically the "My Documents" folder 4 on Windows, and the user's home directory 3 on Unix. If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.

That being said, I'd pay attention 2 to the highlighted text since it appears that you're setting 1 a file as the current directory and not a directory.

Score: 1

In your main class declare

public static String dirpath=".";

private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {    
 JFileChooser jfc = new JFileChooser(dirpath);
 dirpath =jfc.getSelectedFile().getAbsolutePath().toString();


Score: 1

For select the last directory that you open 1 :


int r = chooser.showOpenDialog(new JPanel());

if (r == JFileChooser.APPROVE_OPTION) {
   fileName = chooser.getSelectedFile().getPath();
   lastDirectory = chooser.getSelectedFile();
Score: 1

JFileChooser Chooser = new JFileChooser("F:");


Score: 0

if you want to change the directory theb 2 use System.getProperty method

String s=System.getProperty("user.dir");  // changes directory from documents to the user current Directory;

JFileChooser 1 jfc=new JFileChooser(s);

More Related questions