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

Mike2012 picture Mike2012 · Aug 3, 2009 · Viewed 10.7k times · Source

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).

Answer

Ben S picture Ben S · Aug 3, 2009

Assuming you're determined to use the FileDialog instead of the portable JFileChooser, you need to set the system property so that FileDialogs created are for directories.

The property in question is apple.awt.fileDialogForDirectories.

So simply do the following:

System.setProperty("apple.awt.fileDialogForDirectories", "true");
FileDialog fd = new FileDialog(this); 
fd.setDirectory(_projectsBaseDir.getPath()); 
fd.setLocation(50,50);
fd.setVisible(true); 
File selectedFile = new File(fd.getFile());
System.setProperty("apple.awt.fileDialogForDirectories", "false");

It should be noted that this isn't portable, however, since you're looking to replace the portable JFileDialog, I assume that's not an issue.