Java Reference
In-Depth Information
This works essentially the same way as the previous method. You extract each of the color component
values as integers from the corresponding attributes and pass them to the
Color
class constructor.
Creating the
java.awt.Rectangle
object that you need to initialize the
bounds
field is virtually the
same:
// Set bounds field from a node
protected void setBoundsFromXML(Node node) {
NamedNodeMap attrs = node.getAttributes();
bounds = new java.awt.Rectangle(
Integer.valueOf(((Attr)(attrs.getNamedItem("x"))).getValue()),
Integer.valueOf(((Attr)(attrs.getNamedItem("y"))).getValue()),
Integer.valueOf(((Attr)(attrs.getNamedItem("width"))).getValue()),
Integer.valueOf(((Attr)(attrs.getNamedItem("height"))).getValue()));
}
Directory "Sketcher reading and writing XML"
You obtain the four attribute values in exactly the same way as in the other methods.
Creating Elements from XML Nodes
You add a constructor to each of the inner classes of
Element
that has a parameter of type
Node
. The
Node
object passed to each constructor encapsulates the XML child element that was created from an object of
the inner class type. The subclasses of
Element
inherit the methods you have added that initialize the base
class fields, so they can be called from the new constructor. A call to the no-arg
Element
class constructor is
inserted automatically as the first statement in each of the new inner class constructors. Let's start with the
Element.Line
class constructor.
Creating a Line Object from an XML Node
A
Node
object that defines a line has the angle as an attribute, and four child nodes specifying the position,
color, bounds, and the line end point. Here's the constructor to decode that lot:
// Create Line object from XML node
public Line(Node node) {
setAngleFromXML(node);
NodeList childNodes = node.getChildNodes();
Node aNode = null;
for(int i = 0 ; i < childNodes.getLength() ; ++i) {
aNode = childNodes.item(i);
switch(aNode.getNodeName()) {
case "position":
setPositionFromXML(aNode);