Java Reference
In-Depth Information
Node elementNode = null;
for(int i = 0 ; i<nodes.getLength() ; ++i){
// ...process them
elementNode = nodes.item(i);
switch(elementNode.getNodeName()) {
case "line":
model.add(new Element.Line(elementNode));
break;
case "rectangle":
model.add(new Element.Rectangle(elementNode));
break;
case "circle":
model.add(new Element.Circle(elementNode));
break;
case "curve":
model.add(new Element.Curve(elementNode));
break;
case "text":
model.add(new Element.Text(elementNode));
break;
default:
System.err.println("Invalid XML node: " + elementNode);
break;
}
}
}
return model;
}
Directory "Sketcher reading and writing XML"
This method works in a straightforward fashion. You get the child nodes of the root node as a NodeList
object by calling getChildNodes() for the object returned by getDocumentElement() . You determine
what kind of element each child node is by checking its name in the switch statement. You 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 Node object reference that is passed as the argument.
If the child node name does not correspond to any of the sketch elements, you output an error message.
That's all the code you need. If everything compiles, you are ready to try exporting and importing
sketches. If it doesn't compile, chances are good there's an import statement missing. The import state-
ments that I have in SketcherFrame.java now are:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;
import java.nio.file.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import java.awt.print.*;
Search WWH ::




Custom Search