Jans
Jans

Reputation: 35

JFileChooser can't click 'choose'

In my Java program there is a part where the user can choose and change the working directory. The problem is that there is no action performed, when I click on 'choose' after choosing the directory path. The choosing window just stays opened.

However, when I do enter any text in the field "File Name" or choose any file in the directory and do click 'choose' the window is being closed and the directory is chosen.

My code is very simple and I really don't understand why it's not working. You can find my code here:

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   stringHomeDir = chooser.getCurrentDirectory().getPath();
}
...

How can I change it so the user can easily choose a directory in the file chooser?

Upvotes: 1

Views: 426

Answers (2)

Sanjay
Sanjay

Reputation: 61

Change the order of statements and use setSelectedFile(File) method of JFileChooser class.

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

chooser.setSelectedFile(new File(chooser.getCurrentDirectory() + "/" + "Downloads")));

int returnVal = chooser.showOpenDialog(null);

...

'MyDocuments' is a default current directory of JFileChooser and 'Downloads' is a subdirectory of 'MyDocuments'.

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168825

int returnVal = chooser.showOpenDialog(null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

The order of these two statements should be reversed, since the showOpenDilaog method blocks until it closes.

Upvotes: 3

Related Questions