Swing/DirectoryTree の変更点
- 追加された行はこの色です。
- 削除された行はこの色です。
- Swing/DirectoryTree へ行く。
- Swing/DirectoryTree の差分を削除
--- category: swing folder: DirectoryTree title: FileSystemViewを使ってディレクトリ構造をJTreeに表示する tags: [JTree, File, FileSystemView, SwingWorker] author: aterai pubdate: 2011-07-04T16:26:25+09:00 description: FileSystemViewを使ってディレクトリ構造をJTree上に表示します。 image: https://lh3.googleusercontent.com/-FkX-8X4KxDo/ThFoeY8M64I/AAAAAAAAA-Y/Ry_RA9yVCxc/s800/DirectoryTree.png --- * Summary [#summary] `FileSystemView`を使ってディレクトリ構造を`JTree`上に表示します。主に[https://stackoverflow.com/questions/6182110/file-browser-gui java - File Browser GUI - Stack Overflow]を参考にしています。 #download(https://lh3.googleusercontent.com/-FkX-8X4KxDo/ThFoeY8M64I/AAAAAAAAA-Y/Ry_RA9yVCxc/s800/DirectoryTree.png) * Source Code Examples [#sourcecode] #code(link){{ class FolderSelectionListener implements TreeSelectionListener { private final FileSystemView fileSystemView; protected FolderSelectionListener(FileSystemView fileSystemView) { this.fileSystemView = fileSystemView; } @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent(); File parent = (File) node.getUserObject(); // Java 9: // // https://ateraimemo.com/Swing/ResolveShortcutsLinkLocation.html // if (fileSystemView.isLink(parent)) { // try { // parent = fileSystemView.getLinkLocation(parent); // } catch (FileNotFoundException ex) { // return; // } // } if (!node.isLeaf() || !parent.isDirectory()) { return; } JTree tree = (JTree) e.getSource(); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); new BackgroundTask(fileSystemView, parent) { @Override protected void process(List<File> chunks) { if (tree.isDisplayable() && !isCancelled()) { chunks.stream().map(DefaultMutableTreeNode::new) .forEach(child -> model.insertNodeInto( child, node, node.getChildCount())); } else { cancel(true); } } }.execute(); } } }} * Description [#explanation] * Description [#description] このサンプルでは、[https://stackoverflow.com/questions/6182110/file-browser-gui java - File Browser GUI - Stack Overflow]のディレクトリ表示部分を参考にルートパーティション(`Windows`の場合`Desktop`フォルダ)をルートノードにして`JTree`で表示しています。 - クリックされたノードがディレクトリの場合、子ファイルの検索と`JTree`へのそれらの追加を`SwingWorker`を使用して別スレッドで実行するよう変更 * Reference [#reference] - [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/filechooser/FileSystemView.html FileSystemView (Java Platform SE 8)] - [https://stackoverflow.com/questions/6182110/file-browser-gui java - File Browser GUI - Stack Overflow] - [http://www.pushing-pixels.org/2007/07/22/showing-the-file-system-as-a-swing-jtree.html Showing the file system as a Swing JTree ・ Pushing Pixels] - [[JTreeで表示したフォルダ構造でWindowsのlnkショートカット先に移動する>Swing/ResolveShortcutsLinkLocation]] * Comment [#comment] #comment #comment