Java Reference
In-Depth Information
.newDocumentBuilder()
.getDOMImplementation();
doc = domImpl.createDocument(null, "sketch",
domImpl.createDocumentType("sketcher", null, "sketcher.dtd"));
} catch(ParserConfigurationException e) {
e.printStackTrace(System.err);
// Display the error and terminate the current activity...
} catch(DOMException e) {
e.printStackTrace(System.err);
// Determine the kind of error from the error code,
// display the error, and terminate the current activity...
}
They are rather long statements since they accomplish in a single statement what we previously did in
several steps. However, they are quite simple. The first statement creates a
DocumentBuilderFactory object from which a DocumentBuilder object is created from which a
reference DOMImplementation object is obtained and stored in domImpl . This is used in the next
statement to create the Document object for a sketch and its DocumentType object defining the
DOCTYPE declaration for sketcher.dtd . Eventually we will add this code to the SketchModel class
but let's leave that to one side for the moment while we look at how we can fill out the detail of the
Document object from the objects representing elements in a sketch.
A sketch in XML is a simple two-level structure. The root node in an XML representation of a sketch
will be a <sketch> element, so to define the structure we only need to add an Element node to the
content for the root node for each element in the sketch. A good way to implement this would be to add
a method to each of the sketch Element classes that adds its own org.w3c.dom.Element node to
the Document object. This will make each object representing a sketch element able to create its own
XML representation.
The Sketcher classes we have to modify are the inner classes to the Element class, plus the Element class
itself. The inner classes are Element.Line , Element.Rectangle , Element.Circle ,
Element.Curve , and Element.Text . The nodes that have to be added for each kind of geometric
element derive directly from the declaration in the DTD, so it will help if you have this to hand while we go
through these classes. If you typed it in when we discussed it in the last chapter, maybe you can print a copy.
Adding Element Nodes
Polymorphism is going to be a big help in this so let's first define an abstract method in the Element
base class to add an element node to a document. We can add the declaration immediately after the
declaration for the abstract draw() method, like this:
public abstract void draw(Graphics2D g2D);
public abstract void addElementNode(Document document);
Each of the inner classes will need to implement this method since they are derived from the Element class.
We will need a couple of import statement at the beginning of our Element.java file in Sketcher:
Search WWH ::




Custom Search