JFileChooserを開いた時のカレントディレクトリを設定する
Total: 12315, Today: 2, Yesterday: 1
Posted by aterai at 
Last-modified: 
Summary
JFileChooserを開いた時のカレントディレクトリを設定します。
Screenshot

Advertisement
Source Code Examples
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, KotlinDescription
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); } }; 
 - 上記のサンプルで
 
-  JFileChooser#setCurrentDirectory(File)メソッドで
 
setSelectedFile- JFileChooser#setSelectedFile(File)メソッドで選択ファイルとしてディレクトリを設定
 - 参照: コンボボックスには選択ファイルとして設定したディレクトリの親ディレクトリ名
 - リストには親ディレクトリ内のディレクトリ一覧
MetalやNimbus LookAndFeelでは、選択ファイルとして設定したディレクトリが選択状態になるMetalなどのLookAndFeelでもディレクトリが選択状態にならない場合がある- 上記のサンプルで
isParent reset?にチェックをした場合、!fileChooser.getFileSystemView().isParent(fileChooser.getCurrentDirectory(), dir)==falseになるように?setSelectedFileで選択ファイルをリセットする 
 - フォルダ名: テキストフィールドは選択ファイルとして設定したディレクトリ
 - 存在しないディレクトリを
setSelectedFileで設定するとその親ディレクトリ、親ディレクトリも存在しない場合はOSのデフォルトがカレントディレクトリとなる