Java Reference
In-Depth Information
attr.setValue(String.valueOf(this.bounds.width));
bounds.setAttributeNode(attr);
attr = doc.createAttribute("height");
attr.setValue(String.valueOf(this.bounds.height));
bounds.setAttributeNode(attr);
string.appendChild(bounds); // Set <bounds> element as <string> content
string.appendChild(doc.createTextNode(text));
textElement.appendChild(string);// Set <text> as <string> content
doc.getDocumentElement().appendChild(textElement);
}
Since the font style can be "
plain
", "
bold
", "
bold-italic
", or just "
italic
", we have a series of
if
statement to determine the value for the attribute. The style is stored in a
Font
object as an integer
with different values for plain, bold, and italic. The values corresponding to bold and italic can be
combined, in which case the style is "
bold-italic
".
All the element objects in a sketch can now add their own node to a
Document
object. We should now
be able to make a
SketchModel
object use this capability to create a document that encapsulates the
entire sketch.
Creating a Document Object for a Complete Sketch
We can add a
createDocument()
method to the
SketchModel
class to create a
Document
object
and populate it with the nodes for the elements in the current sketch model. Creating the
Document
object will use the code fragment we saw earlier. You need to add some
import
statements at the
beginning of the
SketchModel.java
source file for the new interfaces and classes we will be using:
import javax.swing.JOptionPane;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.DOMException;
Here's the method definition you can add to the class:
// Creates a DOM Document object encapsulating the current sketch
public Document createDocument() {
Document doc = null;
try {
DOMImplementation domImpl = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.getDOMImplementation();
doc = domImpl.createDocument(null, "sketch",
domImpl.createDocumentType("sketcher", null, "sketcher.dtd"));
} catch(ParserConfigurationException e) {
JOptionPane.showInternalMessageDialog(null,
"Parser configuration error while creating document",
"DOM Parser Error",
JOptionPane.ERROR
_
MESSAGE);