Using JTree to display a hierarchy

In the last post we saw how you can easily create a JTree using an array of strings.  The JTree however did not display the values in a hierarchy but displayed all the values at the same level.  So in this post we will build our Java Desktop Application using JTree with a hierarchy.

JTree Hierarchy using TreeNode

Now if we follow on from our previous example of building a JTree from an array we could go about it like this:

But the result of this is not quite what we are looking for:

JTree Hierarchy using String Array

If we want to build a JTree with a hierarchy then we need to use Tree Nodes.  There are a two TreeNode interfaces provided in the swing package, TreeNode and MutableTreeNode as well as a concrete class DefaultMutableNode.

So, we could build our own implementation of TreeNode and implement one or both of the interfaces or we can, given our simple needs, build the hierarchy using the DefaultMutableTreeNode like this:

Here we create a DefaultMutableTreeNode for each of the parent nodes.  We can then add children and nodes to a parent.

Another difference is the constructor we now use means the JTree is created using a node set as the root and will display this by default.

In the previous example the constructor used resulted in hiding the root node by default, in this case we explicitly created a root node and therefore have to hide it using setRootVisible(false).

The use of the constructor means that we also do not get handles to expand and collapse the nodes with children, to get that to display we call the setShowsRootHandles(true).

The result we get is:

JTree Hierarchy using TreeNode

Now all this is fine but, usually when we use a JTree it is because we want to be able to select an item, one or more and display additional information based on the selection.  In the next posting we will take a look how we can accomplish this.

Download the source code for this JTree example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.