JFileChooser returns wrong path in OS X (folder-only mode)

I have a problem with java swing where the user must select a folder, so I use 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 two ways that a user can select a folder

  • Go to the folder and select the folder
  • Go to the folder, go to the folder and click

Both methods 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 to avoid this second case?

Thanks in advance.

+3
source share
1 answer

, showDialog , , /. " " ( ), SELECT, , .

, showOpenDialog SELECT. , .

:

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";
}
+6

Source: https://habr.com/ru/post/1750538/


All Articles