Java Reference
In-Depth Information
break;
case "color":
setColorFromXML(aNode);
break;
case "bounds":
setBoundsFromXML(aNode);
break;
case "endpoint":
NamedNodeMap coords = aNode.getAttributes();
line = new Line2D.Double();
line.x2 =
Double.valueOf(((Attr)(coords.getNamedItem("x"))).getValue());
line.y2 =
Double.valueOf(((Attr)(coords.getNamedItem("y"))).getValue());
break;
default:
System.err.println("Invalid node in <line>: " + aNode);
break;
}
}
}
Directory "Sketcher reading and writing XML"
You set the angle for the line by calling the method that you added to the base class for this purpose.
The
getChildNode()
method returns the child nodes in a
NodeList
object. You iterate over all the nodes
in the
childNodes
list in the
for
loop. Calling
getItem()
for
childNodes
returns the
Node
object at the
index position you pass to the method. You then process the node in the
switch
statement, selecting on the
basis of the node name, which is a
String
. Each of the base class fields are set by calling one or other of
the methods you have defined. For the
<endpoint>
node, you reconstruct the
Line2D.Double
object from
the attributes for the node. Calling the no-arg constructor for
Line2D.Double
creates an object with the start
and end points as (0,0), so you just have to set the end point coordinates, which are stored in
line.x2
and
line.y2
.
Creating a Rectangle Object from an XML Node
Most of the code to reconstruct an
Element.Rectangle
object is the same as for a line:
// Create Rectangle object from XML node
public Rectangle(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);