Question

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.

Was it helpful?

Solution

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";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top