Java Reference
In-Depth Information
Exporting a Sketch as XML
To export a sketch as XML, you can use the
showDialog()
method that creates a file chooser dialog to
identify the file for the XML markup output. The dialog uses a new file filter that you can define as a field
in the
SketcherFrame
class:
private ExtensionFilter xmlFileFilter = new ExtensionFilter(
".xml", "XML Sketch files (*.xml)");
This defines a filter for files with the extension
.xml
. The
showDialog()
method should ensure that a
selected file path ends in XML when the
xmlFileFilter
is in effect because this is an indicator that the dia-
log is used for an XML file operation. You can implement this by adding a statement to the
showDialog()
method:
Path selectedFile = null;
if(file == null) {
selectedFile = Paths.get(
fileChooser.getCurrentDirectory().toString(), DEFAULT_FILENAME);
} else {
selectedFile = file;
}
selectedFile = setFileExtension(
selectedFile, filter == xmlFileFilter ? ".xml" : ".ske");
fileChooser.setSelectedFile(new File(selectedFile.toString()));
The second argument to the
setFileExtension()
method call is
".xml"
when the XML file filter is
in effect and
".ske"
otherwise. Note that this only guarantees that the file that is initially selected has the
extension .xml. The path that is returned may not.
You can implement the method to export a sketch as XML in the
SketcherFrame
class like this:
// Export a sketch as XML
private void exportXMLOperation() {
Path selectedFile = null;
if(currentSketchFile == null) {
selectedFile = Paths.get(
fileChooser.getCurrentDirectory().toString(), DEFAULT_FILENAME);
} else {
selectedFile = currentSketchFile;
}
// Make extension .xml
selectedFile = setFileExtension(selectedFile, ".xml");
Path file = showDialog("Export Sketch as XML", "Export",
"Export sketch as XML", xmlFileFilter, selectedFile);
if(file == null) {
// No file selected...
return;
// ... so we are done.
}
if(Files.exists(file) &&
// If the path exists and...