Java Reference
In-Depth Information
}
}
Directory "Sketcher reading and writing XML"
The process for extracting child nodes from the
Node
object passed to the constructor is as you have seen
for the other constructors. For the
<string>
child node, you call its
getTextContent()
method to obtain
the text for the object. You call a new method that creates the font field from a node corresponding to a
<font>
child element. You can add the
setFontFromXML()
method to the
Element.Text
class like this:
// Set the font field from an XML node
private void setFontFromXML(Node node) {
NamedNodeMap attrs = node.getAttributes();
String fontName = ((Attr)(attrs.getNamedItem("fontname"))).getValue();
String style = ((Attr)(attrs.getNamedItem("fontstyle"))).getValue();
int fontStyle = 0;
switch(style){
case "plain":
fontStyle = Font.PLAIN;
break;
case "bold":
fontStyle = Font.BOLD;
break;
case "italic":
fontStyle = Font.ITALIC;
break;
case "bold-italic":
fontStyle = Font.ITALIC|Font.BOLD;
break;
default:
System.err.println("Invalid font style code: " + style);
break;
}
int pointSize =
Integer.valueOf(((Attr)(attrs.getNamedItem("pointsize"))).getValue());
font = new Font(fontName, fontStyle, pointSize);
}
Directory "Sketcher reading and writing XML"
The font name, style, and point size are all recorded as attributes for the
<font>
XML node. The font
style is recorded as one of four possible strings, so for each of these you set the value of the
fontStyle
variable to the corresponding integer constant from the
Font
class. Because you need to extract the node
attributes directly here, you extract the
angle
value along with the other attributes, rather than calling the
base class method.
That completes creating sketch elements from XML nodes. The final piece is to handle the Import XML
menu item event.