Java Reference
In-Depth Information
Serializing the Sketch
Our Sketcher program can only be considered to be a practical application if we can save sketches in a
file and retrieve them later - in other words we need to implement serialization for a SketchModel
object and use that to make the F ile menu work. Ideally, we want to be able to write the model for a
sketch to a file and be able to read it back at a later date and reconstruct exactly the same model object.
This naturally leads us to choose serialization as the way to do this, because the primary purpose of
serialization is the accurate storage and retrieval of objects.
We've seen how to serialize objects, back in Chapter 11. All we need to do to serialize a sketch
document in our Sketcher program is to apply what we learned there. Of course, there are quite a few
classes involved in a sketch document but it will be remarkably easy, considering the potential
complexity of a sketch - I promise!
Of course, saving a sketch on disk and reading it back from a file will be significantly more work than
implementing serialization for the document. The logic of opening and saving files so as not to lose
anything accidentally can get rather convoluted. Before we get into that, there is a more fundamental
point we should address - our sketch doesn't have a name. We should at least make provision for
assigning a file name to a sketch, and maybe display the name in the title bar of the application window.
Try It Out - Assigning a Document Name
Since the sketch is going to have a name, because we intend to store it somewhere, let's define a default
directory to hold sketches. Add the following lines to the end of the Constants interface
( Constants.java ):
File DEFAULT _ DIRECTORY = new File("C:/Sketches");
String DEFAULT _ FILENAME = "Sketch.ske";
If you want to store your sketches in a different directory you can set the definition of
DEFAULT _ DIRECTORY to suit your needs. The file extension, .ske , to identify sketches is also
arbitrary. You can change this if you would prefer to use a different extension. Since we reference the
File class here, we must add an import statement to the Constants source file to get at it:
import java.io.File;
We can now add the following data members to the SketchFrame class definition:
private String frameTitle; // Frame title
private String filename = DEFAULT _ FILENAME; // Current model file name
private File modelFile; // File for the current sketch
The frameTitle member specifies the basic title for the Sketcher application window. We will append
the file name for the sketch to it. The modelFile member will hold a reference to the File object
identifying the file containing the current sketch, once the sketch has been saved. At this point you can
update the import statements for the SketchFrame class to import all the classes from the java.io
package as we will be using quite a few more of them in this chapter:
Search WWH ::




Custom Search