views:

99

answers:

1

I have a problem in java swing where the user has to select a folder, so I am using the code below.

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

if(fc.showDialog(singleton, SELECT) == JFileChooser.APPROVE_OPTION) {
  File folder = fc.getSelectedFile();
  String path = folder.getPath() + File.separatorChar + MYAPPFOLDER;
}

Now there are 2 ways a user may select the folder

  1. Navigate to the folder and select the folder
  2. Navigate to the folder, go into the folder, and click select

Both ways work fine on windows but on OS X, I get

If I do 1 : path = Users/<username>/Desktop/MYAPPFOLDER

If I do 2 : path = Users/<username>/Desktop/Desktop/MYAPPFOLDER

How do I avoid this 2nd case?

Thanks in advance.

+3  A: 

The problem is that showDialog doesn't know whether this is a load or save operation, so it gives you the textbox to put the new file/folder name in. This is set to 'Desktop' when you click on the folder to go into it (as the first click of a double-click) and if the user then presses SELECT, the dialog assumes you want to create a new folder with that name and returns it in the path.

One solution is to use the showOpenDialog call instead, and manually change the chooser's title and approve buttons to SELECT. That way, the user never sees the new directory textbox.

The code would look something like this:

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

fc.setDialogTitle("Select a folder");
fc.setApproveButtonText(SELECT);
if(fc.showOpenDialog(singleton) == JFileChooser.APPROVE_OPTION) {
  File folder = fc.getSelectedFile();
  String path = folder.getPath() + File.separatorChar + "MYAPPFOLDER";
}
Pat Wallace
I wasn't originally going to upvote this, then I saw in the Javadoc that setting custom approve button text defaults the dialog type to `JFileChooser.CUSTOM_DIALOG` (the default is open dialog).
R. Bemrose