如何在OS X中将java FileDialog接受目录作为其FileType?

当我的应用程序在Mac上运行时,我试图从使用JFileChooser切换到FileDialog,以便它将使用OS X文件选择器。 到目前为止,我有以下代码:

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

我会为这个问题投入什么? 所以我的文件选择器将允许任何目录作为文件选择器的输入(后面的方法已经检查以确保该目录是我想让FileDialog接受任何目录的正确类型的目录)。

假设您决定使用FileDialog而不是可移植的JFileChooser,则需要设置系统属性,以便为目录创建FileDialogs。

有问题的属性是apple.awt.fileDialogForDirectories

所以只需执行以下操作:

 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"); 

应该注意的是,这不是便携式的,但是,因为您正在寻找替换便携式JFileDialog,我认为这不是问题。

当我的应用程序在mac上运行时,我试图从使用JFileChooser切换到FileDialog,以便它将使用OSx文件选择器

我建议你试着留在Swing世界,并避开重量级的AWT世界。 有很多方法可以解决Mac上Swing L&F的问题,如果这就是你的问题。 看一下之前的问题 ,该问题链接到一个网站,该网站显示如何在文件选择器中获取正确的Mac图标。

请原谅我没有完全回答你的问题。 如果您还有其他原因希望继续使用FileDialog ,我很乐意删除此post。

使用最流行的解决方案后:

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

我无法解决本机FileDialog实现的按钮(仅限英语)的翻译。

所以我得到一个在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; 

请享用!