January 27, 2021
Hot Topics:

Displaying XML in a Swing JTree, Page 3

  • By Rob Lybarger
  • Send Email »
  • More Articles »

The final method is not needed for the purposes of the demo because you are not allowing edits to be made to the tree. Therefore, a dummy implementation is given:

public void valueForPathChanged(TreePath path, Object
   newValue) {
   throw new UnsupportedOperationException();

That's everything you need. The rest just involves a little code to create a demo interface with a JTree in it, to load an XML-formatted file into a Document object, and to pass this off to an XMLTreeModel instance. I will leave most of these details for the reader to experiment with, but will offer at least one parting screenshot. Consider the following XML document:

<?xml version="1.0"?>
   <settings>This is a test.</settings>
      <title>My Title</title>
      <info>The quick brown fox jumps over the lazy dog.</info>

An interface that includes the JTree itself (and also includes code that listens for user selections of nodes in the tree to display text content into a standard JTextField) is available in the downloadable code bundle. The screenshot on a Mac system looks as follows:


Writing a custom data model to display an XML document in a Swing JTree is ultimately rather easy. It's certainly easier than trying to get the "DefaultXXX" convenience classes to work off of the same data source. (How easy it is to sometimes forget this and try to shoehorn a problem into a convenience implementation for which it wasn't designed!) Of course, care must be exercised to clearly identify just exactly what parts of the XML document need to be diplayed, and this should be clearly spelled out before the TreeModel implementation is written. (For this demo, all Element-type nodes in the document were shown in the tree.)

Download the Code

You can download the code that accompanies this article here.

About the Author

Rob Lybarger is a software guy (and a degreed aerospace engineer) in the Houston, TX area who has been using Java for nearly ten years. He has used various versions of Windows, various distributions of Linux, but loves Mac OS X. He likes exploring new techniques and new approaches to organizing and wiring applications, and loves to let the computer do as much work for him as possible.

Page 3 of 3

This article was originally published on March 3, 2008

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date