JFileChooserのPlacesBarショートカットの初期値を変更する
Total: 1561, Today: 1, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JFileChooserのPlacesBarショートカットフォルダの初期値をドキュメントからPCに変更します。
Screenshot

Advertisement
Source Code Examples
JButton button2 = new JButton("ShellFolder.get(\"fileChooserShortcutPanelFolders\")");
button2.addActionListener(e -> {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FileSystemView fsv = chooser.getFileSystemView();
File[] files = (File[]) ShellFolder.get("fileChooserShortcutPanelFolders");
chooser.addHierarchyListener(ev -> {
Component c = ev.getComponent();
if ((ev.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing()) {
Class<JToggleButton> clz = JToggleButton.class;
descendants(chooser)
.filter(clz::isInstance).map(clz::cast)
.filter(rb -> fsv.getSystemDisplayName(files[3]).equals(rb.getText()))
.findFirst().ifPresent(AbstractButton::doClick);
}
});
chooser.showOpenDialog(getRootPane());
});
View in GitHub: Java, KotlinDescription
DefaultWindows 10環境でWindowsLookAndFeelを適用したJFileChooserのPlacesBarには「最近使った項目(Recent)」、「デスクトップ(Desktop)」、「ドキュメント(Document)」、「PC(This PC)」、「ネットワーク(Network)」が表示され、デフォルトでは「ドキュメント」が選択状態になる
System.getenv("SystemDrive")System.getenv("SystemDrive") + File.separatorCharでC:\ドライブのFileを取得し、その親フォルダをFileSystemView#getParentDirectory(...)メソッドで取得- この親フォルダが「
PC(This PC)」となるのでJFileChooser#setCurrentDirectory(...)で設定してからJFileChooserを開く - java - How to make JFileChooser Default to Computer View instead of My Documents - Stack Overflow
ShellFolder.get("fileChooserShortcutPanelFolders")ShellFolder.get("fileChooserShortcutPanelFolders")でショートカットフォルダ一覧をFile配列で取得PlacesBarのショートカットはJToggleButtonで作成されているのでJFileChooserにHierarchyListenerを追加してダイアログが表示状態になったらその子コンポーネントを検索FileSystemView#getSystemDisplayName(File)で取得可能なシステム表示名が一致するボタンテキストのJToggleButtonを発見したらdoClick()を実行- Containerの子Componentを再帰的にすべて取得する
Reference
- java - How to make JFileChooser Default to Computer View instead of My Documents - Stack Overflow
- Containerの子Componentを再帰的にすべて取得する