10

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

4

3 に答える 3

11

ポータブルJFileChooserの代わりにFileDialogを使用することにした場合は、作成されたFileDialogがディレクトリ用になるようにシステムプロパティを設定する必要があります。

問題のプロパティはです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を置き換えることを検討しているため、これは問題ではないと思います。

于 2009-08-03T21:35:32.197 に答える
1

アプリをMacで実行しているときに、JFileChooserの使用からFileDialogに切り替えて、OSxファイルチューザーを使用するようにしようとしています。

Swingの世界にとどまり、AWTのより重い世界から遠ざかることをお勧めします。それがあなたの問題であるならば、Mac上のSwing L&Fの問題を回避する方法があります。ファイルチューザーで正しいMacアイコンを取得する方法を示すサイトにリンクしている以前の質問へのこの投稿を見てください。

あなたの質問に正確に答えていないので失礼します。あなたがとどまりたいと思う他の理由があるならばFileDialog、私は喜んでこの投稿を削除します。

于 2009-08-03T21:36:27.140 に答える
1

最も人気のあるソリューションをしばらく使用した後:

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;

楽しみ!

于 2017-09-17T14:37:23.500 に答える