Java Reference
In-Depth Information
// Content is <color>, <position>, <endpoint> elements. Attribute is angle.
public Line(org.w3c.dom.Element xmlElement) {
super(xmlElement);
org.w3c.dom.NodeList list = xmlElement.getElementsByTagName("endpoint");
org.w3c.dom.Element endpoint = (org.w3c.dom.Element)list.item(0);
line = new Line2D.Double(origin.x, origin.y,
Double.parseDouble(endpoint.getAttribute("x"))-position.getX(),
Double.parseDouble(endpoint.getAttribute("y"))-position.getY());
}
To save having to refer back to the DTD, the first comment in the constructor outlines the XML
corresponding to the element. We first call the base class constructor and then extract the child element that
is the <endpoint> element. You will doubtless recall that all our sketch elements are defined at the origin.
This makes moving an element very easy and allows all elements to be moved in the same way - by
modifying the position field. We therefore create the Line2D.Double object as a line starting at the
origin. The coordinates of its end point are the values stored in the <endpoint> child element minus the
corresponding coordinates of position that were set in the base class constructor.
Creating a Rectangle Element
This constructor will be almost identical to the previous constructor for a line:
// Rectangle has angle attribute. Content is <color>,<position>,<bottomright>
public Rectangle(org.w3c.dom.Element xmlElement) {
super(xmlElement);
org.w3c.dom.NodeList list = xmlElement.getElementsByTagName("bottomright");
org.w3c.dom.Element bottomright = (org.w3c.dom.Element)list.item(0);
rectangle = new Rectangle2D.Double(origin.x, origin.y,
Double.parseDouble(bottomright.getAttribute("x"))-position.getX(),
Double.parseDouble(bottomright.getAttribute("y"))-position.getY());
}
Spot the differences! This code is so similar to that of the Line constructor that I don't think it requires
further explanation.
Creating a Circle Element
Here's the code for the Circle constructor:
// Circle has radius, angle attributes. Content is <color>, <position>
public Circle(org.w3c.dom.Element xmlElement) {
super(xmlElement);
double radius = Double.parseDouble(xmlElement.getAttribute("radius"));
circle = new Ellipse2D.Double(origin.x, origin.y, // Position - top-left
2.*radius, 2.*radius ); // Width & height
}
Search WWH ::




Custom Search