Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a java FileDialog accept directories as its FileType in OS X?

I am trying to switch from using a JFileChooser to a FileDialog when my app is being run on a mac so that it will use the OS X file chooser. So far I have the following code:

    FileDialog fd = new FileDialog(this);
    fd.setDirectory(_projectsBaseDir.getPath());
    fd.setLocation(50,50);
    fd.setFile(?);
    fd.setVisible(true);
    File selectedFile = new File(fd.getFile());

What would I put in for the question ? so that my file chooser would allow any directory to be the input for file chooser (the method that follows already checks to make sure that the directory is the right kind of directory I just want to the FileDialog to accept any directory).

like image 503
Mike2012 Avatar asked Aug 03 '09 21:08

Mike2012


1 Answers

After using most popular solution for while:

System.setProperty("apple.awt.fileDialogForDirectories", "true");

I can't resolve translation of Buttons (only in English) of native FileDialog implementation.

So I get a workaround that works perfectly on macOS:

try {
    Process process = Runtime.getRuntime().exec(new String[]{//
        "/usr/bin/osascript", //
        "-e", //
        "set selectedFolder to choose folder\n"//
        + "return POSIX path of selectedFolder"
    });
    int result = process.waitFor();
    if (result == 0) {
        String selectedFolder = new BufferedReader(new InputStreamReader(process.getInputStream())).readLine();
        return new File(selectedFolder);
    }
} catch (Exception ex) {
}

return null;

Enjoy!

like image 72
Dyorgio Avatar answered Oct 12 '22 04:10

Dyorgio