• category: swing folder: FileChooserCurrentDirectory title: JFileChooserを開いた時のカレントディレクトリを設定する tags: [JFileChooser] author: aterai pubdate: 2012-09-17T13:37:55+09:00 description: JFileChooserを開いた時のカレントディレクトリを設定します。 image: https://lh5.googleusercontent.com/-L0xUhPSuu1Y/UFaopCvyPFI/AAAAAAAABSg/JUQJkTi-0BI/s800/FileChooserCurrentDirectory.png

概要

JFileChooserを開いた時のカレントディレクトリを設定します。

サンプルコード

File f = new File(field.getText().trim());
JFileChooser fc = check1.isSelected() ? fc2 : fc0;
fc.setCurrentDirectory(f);
int retvalue = fc.showOpenDialog(p);
if (retvalue == JFileChooser.APPROVE_OPTION) {
  log.setText(fc.getSelectedFile().getAbsolutePath());
}
View in GitHub: Java, Kotlin

解説

JFileChooser.DIRECTORIES_ONLYで、ディレクトリのみ表示する場合のカレントディレクトリの設定をテストします。

  • setCurrentDirectory: JFileChooser#setCurrentDirectory(File)CurrentDirectoryを設定
    • 参照: コンボボックスにディレクトリ名
    • リストには、CurrentDirectory内のディレクトリ一覧
    • フォルダ名: テキストフィールドは前回の文字列(setCurrentDirectoryでは変化しない)
    • 存在しないファイルをsetCurrentDirectoryで設定すると、前回のCurrentDirectory(初回に存在しないファイルが設定された場合はOSのデフォルト)が表示される
      • 上記のサンプルで、Change !dir.exists() caseにチェックをした場合、前回のディレクトリではなく、参照可能な親ディレクトリを検索するよう、setCurrentDirectoryをオーバーライドしたJFileChooserを使用する
        JFileChooser fc2 = new JFileChooser() {
          @Override public void setCurrentDirectory(File dir) {
            if (dir != null && !dir.exists()) {
              this.setCurrentDirectory(dir.getParentFile());
            }
            super.setCurrentDirectory(dir);
          }
        };
        
  • setSelectedFile: JFileChooser#setSelectedFile(File)で選択ファイルとしてディレクトリを設定
    • 参照: コンボボックスには、選択ファイルとして設定したディレクトリの親ディレクトリ名
    • リストには、親ディレクトリ内のディレクトリ一覧
      • MetalNimbus LookAndFeelでは、選択ファイルとして設定したディレクトリが選択状態になる
      • MetalなどのLookAndFeelでも、ディレクトリが選択状態にならない場合がある
      • 上記のサンプルで、isParent reset?にチェックをした場合、!fileChooser.getFileSystemView().isParent(fileChooser.getCurrentDirectory(), dir)==falseになるように?setSelectedFileで選択ファイルをリセットする
    • フォルダ名: テキストフィールドは選択ファイルとして設定したディレクトリ
    • 存在しないディレクトリをsetSelectedFileで設定するとその親ディレクトリ、親ディレクトリも存在しない場合は、OSのデフォルトがカレントディレクトリとなる
  • メモ
    • UIManager.getBoolean("FileChooser.usesSingleFilePane")の動作が良く分からない...

コメント