[jdom-interest] ContentList.add and Element.setParent

Hallvard Trætteberg hal at idi.ntnu.no
Tue Sep 24 14:33:46 PDT 2002


I'm writing subclasses of Document, Element and Attribute to support
broadcasting/listening to changes to the JDOM tree. This is useful for
linking a JDOM tree to the user interface components that show parts of it,
e.g. JTree. The idea is to override the main methods used for changing the
tree structure, i.e. adding and removing elements. There are essentially two
1. Overriding ContentList.add(index, object).
This requires replacing the default ContentList of Element, i.e. content =
new MyContentList. To make this a clean technique, Element should have a
protected method createContentList(), to override.
2. Overriding Element.setParent (et. al).
This is what I chose, since it may be used to handle both add and remove
(setParent(null)). There is one important problem, though: ContentList calls
setParent BEFORE adding it the its internal list. Hence, the listeners that
are notified in the overridden setParent, will not really see the newly
added Element, since it is not yet in the parent's list!

I request changing the order to list.add(element);
element.setParent(parent); unless this breaks some other logic in JDOM.
(Interestingly, all but the add(int, Text/CData) methods have this order,
why not that one?). I.e.:

        // check for sanity
        if (parent instanceof Document && indexOfFirstElement() >= 0)
                throw new IllegalAddException(
                  "Cannot add a second root element, only one is allowed");

        // add to list
        list.add(index, element);
        // set document/parent
        if (parent instanceof Document) {
            element.setDocument((Document) parent);
        else {
            element.setParent((Element) parent);


Hallvard Trætteberg, 1. amanuensis ved IDI, NTNU
http://www.idi.ntnu.no/~hal, mailto:hal at idi.ntnu.no, phone:+47 7359 3443

More information about the jdom-interest mailing list