Showing the file system as a Swing JTree

July 22nd, 2007  |  Desktop · Java · Swing · UI

JTree component is very well suited for showing the contents of your file system. In this entry, i’m going to show how you can do it, pointing out a few interesting issues along the way.

The full source for this example can be found here. It contains the following functionality:

  • The FileSystemView object to query the contents of the local file system.
  • The FileTreeCellRenderer to render the single file cell. It has two caches, one for storing the file icon, and another for storing system name for file system root. The second one if very important for performance since on some systems the call to FileSystemView.getSystemDisplayName can take considerable time. Note how we use the FileSystemView.getSystemIcon to show the system-consistent file icon (see screenshot below).
  • The FileTreeNode to present a single tree node. Note that the JTree implementation will not create the entire model (which is very good for the initial state where all the file system roots are collapsed).
  • The main panel that creates the tree, sets the model and the renderer and wraps the tree in a scroll pane. Note that we use File.listRoots to get the file system roots and JTree.setRootVisible(false) to remove the main tree root (so that we have “multi-root” tree, with each file system root being a top-level tree node) – see screenshot below.

Here is how it looks:

File tree panel