[jdom-interest] JTreeOutputter

Chris Robinson chris at iceberg.co.za
Tue Mar 9 02:22:07 PST 2004


I'm new, so hello everyone.

In creating a JTree from a Document, JTreeOutputter requires a root node.
The node tree that results naturally includes this root node and all the
'leaf' nodes (i.e. nodes with no children, just text).

Often the JTree is the left component (inside a JScrollPane) of a
JSplitPane, and the right component is a panel with labels/textfields, etc
that show the XML text, or some modification of it, of the 'leaf' nodes.

So one wants the Document root node to be the JTree's root, not the 'dummy'
node that JTreeOutputter requires, and one doesn't want the 'leaf' nodes

You can use DefaultTreeModel.setRoot() to change the root to the root's
child (the actual Document root), but this unfortunately leaves the original
root in the internal data structure which affects other methods, and you can
use MutableTreeNode.setParent(null) to forcibly obliterate DocumentRoot's
parent, but this is frowned on by DefaultMutableTreeNode.setParent() API

And you can remove the leaf nodes by traversing the tree. But this all takes
extra, perhaps unnecessary code. Here is a possible modification to
JTreeOutputter.java. If you leave out the 'bPruneLeaves' stuff then the code
changes are minimal.

// *********************************************
// org.jdom.contrib.output.JTreeOutputter
// --------------------------------------
// Modified slightly to create a node tree from a Document
// without leaf nodes and return the tree's root node.

-------- snip ---------------

public DefaultMutableTreeNode output(Document doc, boolean bPruneLeaves) {
          return processElement(doc.getRootElement(), null, bPruneLeaves);

public DefaultMutableTreeNode output(Document doc) {
          return processElement(doc.getRootElement(), null, false);

protected DefaultMutableTreeNode processElement(
      Element el, DefaultMutableTreeNode dmtn, boolean bPruneLeaves)
    DefaultMutableTreeNode dmtnLocal = new
    String elText = el.getTextNormalize();
    if (elText != null && !elText.equals(""))
             dmtnLocal.add(new DefaultMutableTreeNode(elText));
    processAttributes(el, dmtnLocal);

    Iterator iter = el.getChildren().iterator();

    while (iter.hasNext())
            Element nextEl = (Element)iter.next();
            if (! bPruneLeaves || nextEl.getChildren().size() > 0)
                         processElement(nextEl, dmtnLocal, bPruneLeaves);

    if (dmtn == null)
           dmtn = dmtnLocal;

     return dmtn;
-------- snip ---------------

 // End org.jdom.contrib.output.JTreeOutputter
 // *********************************************************

Chris Robinson
Iceberg Software

More information about the jdom-interest mailing list