July 28, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Displaying XML in a Swing JTree

  • March 3, 2008
  • 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"?>
<root>
   <settings>This is a test.</settings>
   <body>
      <title>My Title</title>
      <info>The quick brown fox jumps over the lazy dog.</info>
   </body>
</root>

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:

Conclusion

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



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel