The JTree Class

Now that you’ve seen all the tree models and some of the default implementations, let’s look at the visual representation we can give them. The JTree class can build up trees out of several different objects, including a TreeModel. JTree extends directly from JComponent and represents the visual side of any valid tree structure.

As another example of hierarchical data, let’s look at a tree that displays XML documents. (We’ll leave the details of XML to Brett McLaughlin and his excellent Java and XML book. Of course, as our own Bob Eckstein also wrote the XML Pocket Reference, we’ll include a shameless plug for that, too.) Here’s an entirely contrived XML document that contains several layers of data:

<?xml version="1.0"?>
<simple>
 <level1 attr="value" a2="v2">
   This is arbitrary data...
   <emptytag1 />
   <et2 a1="v1"/>
   <level2 more="attributes">
     <input type="text" name="test"/>
   </level2>
 </level1>

 <!-- one more level to test...--><test/>
 <one>
  <two>
   <three>
    <four/>
    <five/><fiveA/>
   </three>
   <six/>
   <seven>
    <eight/>
   </seven>
  </two>
  <nine/>
 </one>
 <multi><line>test</line></multi>
</simple>

Figure 17-6 shows the representation of this document in a JTree.

A JTree built by parsing an XML document

Figure 17-6. A JTree built by parsing an XML document

In this example, we treat XML tags with children as nodes and tags without children as leaves. Any tag with actual data (not counting the attributes—more on those later) shows ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.