Java Reference
In-Depth Information
System.err.println(e.getMessage());
e.printStackTrace(System.err);
return null;
} catch(DOMException e) {
JOptionPane.showInternalMessageDialog(null,
"DOM exception thrown while creating document",
"DOM Error",
JOptionPane.ERROR
_
MESSAGE);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
return null;
}
// Each element in the sketch can create its own node in the document
Iterator iter = getIterator(); // Iterator for sketch elements
while(iter.hasNext()) // For each element...
((Element)iter.next()).addElementNode(doc); // ...add its node.
return doc;
}
Now notice that this requires the DTD file for sketcher in the same folder as a saved sketch. In our case,
we've made the default
c:\sketches
so a copy will need to be present there.
We now pop up a dialog and return
null
if something goes wrong when we are creating the
Document
object. In case of an exception of type
DOMException
being thrown, you could add a
switch
statement to analyze the value in the
code
member of the exception and provide a more specific
message in the dialog.
The
SketchModel
object can now create a DOM
Document
object encapsulating the entire sketch.
All we now need is some code to use this to write an XML file.
Saving a Sketch as XML
Of course, we could modify Sketcher so that it could save sketches either as objects or as XML, but to
keep things simple we will add menu items to the
F
ile
menu to export or import a sketch as XML. In
broad terms, here's what we have to do to the
SketchFrame
class to save a sketch as an XML file:
Add
Import XML
and
Export XML
menu items.
❑
Add XML
ImportAction
and
XMLExportAction
inner classes defining the
Action
types
for the new menu items, either to save the current sketch as an XML file or to replace the
current sketch by a new sketch created from an XML file.
❑
Implement the process of creating an XML document as text from the
Document
object
created by the
createDocument()
method that we added to the
SketchModel
class.
❑
Implement writing the text for the XML document to a file.
❑