Java Reference
In-Depth Information
protected void save() {
int status = fc().showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
File f = fc.getSelectedFile();
ObjectOutputStream out =
new ObjectOutputStream(
new FileOutputStream(f));
out.writeObject(/* ? */);
catch (IOException e)
// explain the problem and offer to try again
protected JFileChooser fc()
if (fc == null)
fc = new JFileChooser();
return fc;
The save() method uses a JFileChooser dialog to determine where the user wants to
save the simulation state. The ObjectOutputStream class, from , provides
the ability to write an object to disk.
What object should the save() method write out?
For the save() method to work correctly, the MachineImage class must implement the
Serializable interface, and the class's persistent attributes must also be serializable. If
you inspect the code in the visualization package, you will find that the
MachineImage class marks its image attribute as transient . This causes a serialization
of a MachineImage class to not save the image attribute. The class lazy-initializes its
image from the image's file name, so when a MachineImage object is restored, the image is
rebuilt from the original graphics file. (This requires that the image exist in the class path of
the Visualization2 class.)
To allow users to restore a previously constructed simulation, the File menu offers a Load
item that calls a load() method. The load() method is parallel in design to the save()
method but uses the classes ObjectInputStream and FileInputStream instead of
their Output counterparts to retrieve a visualization's prior state. The load() method
empties the mementos stack, pushes the retrieved memento, disables the Undo button, and
calls the FactoryModel class's restore() method:
Search WWH ::

Custom Search