By Alvin Alexander. Last updated: June 6, 2016
The following code is a “show file dialog” method that works on Mac OS X. I wrote the code a long time ago, but this still looks like the preferred way to show a file-chooser dialog on OS X, as of Java 7 and Mac OS X 10.9 and 10.10.
Here’s the Java source code:
/** * @param frame - parent frame * @param dialogTitle - dialog title * @param defaultDirectory - default directory * @param fileType - something like "*.jpg" * @return Returns null if the user selected nothing, otherwise returns the canonical filename (directory + fileSep + filename). */ String showFileDialog (Frame frame, String dialogTitle, String defaultDirectory, String fileType) { FileDialog fd = new FileDialog(frame, dialogTitle, FileDialog.LOAD); fd.setFile(fileType); fd.setDirectory(defaultDirectory); fd.setLocationRelativeTo(frame); fd.setVisible(true); String directory = fd.getDirectory(); String filename = fd.getFile(); if (directory == null || filename == null || directory.trim().equals("") || filename.trim().equals("")) { return null; } else { // this was not needed on mac os x: //return directory + System.getProperty("file.separator") + filename; return directory + filename; } }