Java Reference
In-Depth Information
model.add(new Element.Circle((org.w3c.dom.Element)node));
else if(name.equals("curve")) // Check for a curve
model.add(new Element.Curve((org.w3c.dom.Element)node));
else if(name.equals("text")) // Check for a text
model.add(new Element.Text((org.w3c.dom.Element)node));
node = node.getNextSibling(); // Next child node
}
return model;
}
This works in a straightforward fashion. We get the first child node of the root node by calling
getDocumentElement() for the document object to obtain a reference to the
org.w3c.dom.Element object that encapsulates the root node, then call its getFirstChild()
method to obtain a reference of type Node to its first child. All the children of the root element should
be Element nodes, and the assertion verifies this.
We determine what kind of element each child node is by checking its name. We call a sketch Element
constructor corresponding to the node name to create the sketch element to be added to the model. Each of
these constructors creates an object from the org.w3c.dom.Element object reference that is passed as the
argument. We just have to implement these constructors in the subclasses of Element and we are done.
Creating Sketch Elements from XML Elements
Every element has to have the color field in the base class set to a color determined from a <color>
element in the document. We can therefore usefully add a base class method to take care of this. Add
the following to the Element class definition:
protected void setElementColor(org.w3c.dom.Element colorElement) {
color = new Color(Integer.parseInt(colorElement.getAttribute("R")),
Integer.parseInt(colorElement.getAttribute("G")),
Integer.parseInt(colorElement.getAttribute("B")));
}
The method expects to receive a reference to an org.w3c.dom.Element object as an argument that
contains the RGB values for the color. We extract the value of each of the attributes in the
colorElement object by calling its getAttribute() method with the attribute name as the
argument. We pass each of the values obtained to the Color constructor and we store the reference to
this object in color . Because the attribute values are strings, we have to convert them to numerical
values using the static parseInt() method that is defined in the Integer class.
The same applies to the position field in the Element class, so we will define a method in the Element
class to initialize it from an org.w3c.dom.Element object:
protected void setElementPosition(org.w3c.dom.Element posElement) {
position = new Point();
position.setLocation(Double.parseDouble(posElement.getAttribute("x")),
Double.parseDouble(posElement.getAttribute("y")));
}
Search WWH ::




Custom Search