Building a Tree Viewer

Viewing Hierarchical Relationships Graphically in Java Without Using Swing JTree

by Daniel Dee

The Java Foundation Class, also known as Swing, in addition to augmenting, enhancing and generally implementing platform-independent replacements of AWT components, also added the JTree class to its repertoire of new GUI components. Swing's JTree supports a Windows Explorer-style (outliner-style) tree that makes it very easy to graphically render data with hierarchical relationship. A limited number of graphical attributes as supplied by the default look-and-feel provided with Swing - e.g., the icon representing the nodes - is also readily configurable.

This article describes an implementation similar to JTree that can be used in Java 1.02 or when using Swing may not be an option. This implementation also added features not found in the default JTree. These include the option of rendering a tree vertically or horizontally, and of aligning it left, center or right. In addition, subtrees can be interactively moved from one branch to another using drag-and-drop. The source code in this article requires the Callbackable, CallbackList, Widget, PositionableGridConstraints and PositionableGridLayout classes introduced in previous issues of JDJ.

Tree Viewer Example

Figure 1: Tree Viewer Example

Genuine Running Java Applet: TreeViewerTest

Brief Description
This applet lets you create a vertically oriented, center-aligned tree using widgetized Buttons as nodes. To create a child, click on the button that is to be its parent. You many drag an entire subtree over to another branch. Dragging is accomplished by holding down the mouse button near the Button to be dragged. The red rectangle will trace out the drag path as long as the mouse button is held down. Releasing the mouse button on top of any other Buttons move the entire subtree to the new location.

This article is published in April 1999 of the Java Developer's Journal.

Source code associated with this article has been obsoleted and is no longer supported.