Java Reference
In-Depth Information
fileMenu.add(printSetupItem); // Print page setup menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(exitAction); // Print sketch menu item
menuBar.add(fileMenu); // Add the file menu
}
Directory "Sketcher 10 with printer page setup"
The new menu item has a tooltip. The action events for the
printSetupItem
are handled by an anonym-
ous class object. It references the
printJob
object to call its
pageDialog()
method, which displays a dia-
log for setting up the printed page. Data from the
PageFormat
object you supply as the argument is used
to set the values in controls in the dialog. The
PageFormat
object that
pageDialog()
returns is stored in
pageFormat
. This is the updated
PageFormat
object if the user makes changes and selects the OK button,
or the original object that was the argument if the dialog is canceled.
For the
printJob
and
pageFormat
objects to be accessible here, you can make them members of the
SketcherFrame
class, along with the
PrintService
object. Add the following class members to
Sketch-
erFrame
:
private PrinterJob printJob;
// The current printer job
private PageFormat pageFormat;
// The printing page format
private PrintService printer;
// The printer to be used
Directory "Sketcher 10 with printer page setup"
You can initialize the first two fields in the
SketcherFrame
constructor. Add the following statements at
the beginning of the code in the constructor:
printJob = PrinterJob.getPrinterJob();
// Get a printing object
pageFormat = printJob.defaultPage();
// Get the page format
printer = printJob.getPrintService();
// Get the default printer
Directory "Sketcher 10 with printer page setup"
The fields concerned with printing are now accessible from anywhere in the
SketcherFrame
class code,
including the inner classes such as the
FileAction
class.
You need to change the code in the
actionPerformed()
method in the
FileAction
class to make use of
the fields you have just added to the
SketcherFrame
class. This involves deleting the first two statements
in the block dealing with
printAction
events that initialize
printJob
and
printService
, and deleting the