Java Reference
In-Depth Information
JOptionPane.showMessageDialog(this,
"Parser configuration error while creating
document",
"DOM Parser Error",
JOptionPane.ERROR_MESSAGE);
System.err.println(pce.getMessage());
pce.printStackTrace();
return null;
} catch(DOMException de) {
JOptionPane.showInternalMessageDialog(null,
"DOM exception thrown while creating
document",
"DOM Error",
JOptionPane.ERROR_MESSAGE);
System.err.println(de.getMessage());
de.printStackTrace();
return null;
}
// Each element in the sketch can create its own node in the document
SketcherModel elements = theApp.getModel(); // Get the sketch
for(Element element : elements) {
// For each element...
element.addElementNode(doc);
// ...add its node.
}
return doc;
}
Directory "Sketcher reading and writing XML"
Notice that this assumes that the DTD file for Sketcher should be in your
Beg Java Stuff
folder. If it
isn't, amend the code accordingly. You call
setErrorHandler()
for the
DocumentBuilder
object to make
the
SketcherFrame
object the handler for parsing errors. This implies that you must make the
Sketcher-
Frame
class implement the
ErrorHandler
interface.
You pop up a dialog and return
null
if something goes wrong when you are creating the
Document
object.
In case of a
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.
To implement the
ErrorHandler
interface, first amend the first line of the
SketcherFrame
class defini-
tion:
public class SketcherFrame extends JFrame
implements ActionListener, Observer, Printable, ErrorHandler {
Now you can add the following three method definitions that are required:
// Handles recoverable errors from parsing XML
public void error(SAXParseException spe) {
JOptionPane.showMessageDialog(SketcherFrame.this,
"Error at line " + spe.getLineNumber() + "\n" +
spe.getMessage(),