Java Reference
In-Depth Information
Chapter 21
Filing and Printing Documents
WHAT YOU WILL LEARN IN THIS CHAPTER:
• How to use the JFileChooser class
• How to save a sketch in a file as objects
• How to implement the Save As menu mechanism
• How to open a sketch stored in a file and integrate it into the application
• How to create a new sketch and integrate it into the application
• How to ensure that the current sketch is saved before the application is closed or a new sketch is
loaded
• How printing in Java works
• How to print in landscape orientation rather than portrait orientation
• How to implement multipage printing
• How to output Swing components to your printer
In this chapter, you explore serializing and printing documents in an application, and you add these capab-
ilities as the finishing touches to the Sketcher program. Neither serialization nor printing are available to an
untrusted applet for security reasons, so everything I cover in this chapter applies only to applications and
trusted applets. Although you have already covered serialization in Chapter 12, you'll find that there is quite a
difference between understanding how the basic methods for object input and output work and applying them
in a practical context.
SERIALIZING THE SKETCH
The Sketcher program can be considered to be a practical application only if you can save sketches in a file
and retrieve them later — in other words, you need to implement serialization for a SketcherModel object
and use that to make the File menu work. Ideally, you 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. The basics are
already in place. You have declared that the SketcherModel class and the Element class, and therefore its
subclasses implement the Serializable interface. You now need to make sure that the other conditions for
serialization are met; namely that all the fields in the classes meet the requirements of serialization, too.
Implementing Serialization
Search WWH ::




Custom Search