Java Reference
In-Depth Information
The code that you added to the
actionPerformed()
method in the
FileAction
inner class to
Sketcher-
Frame
identified the
SketcherView
object to the
PrinterJob
object as responsible for executing the print-
ing of a page. The
PrinterJob
object therefore calls the
print()
method that you have defined here for
each page to be printed. This process starts when you call the
print()
method for the
PrinterJob
object
that has overall control of the printing process.
You can see that the
print()
method in
SketcherView
can throw an exception of type
PrinterExcep-
tion
. If you identify a problem within your
print()
method code, the way to signal the problem to the
PrinterJob
object is to throw an exception of this type.
NOTE
Keep in mind that you cannot assume that the
PrinterJob
object calls the
print()
methodforyour
Printable
objectjustonceperpage.Ingeneral,the
print()
methodislikely
tobecalledseveraltimesforeachpagebecausetheoutputtotheprinterisbufferedwithinthe
Java printing system, and the buffer is not necessarily large enough to hold a complete page.
You don't need to worry about this unduly. Just don't build any assumptions into your code
about how often
print()
is called for a given page.
Of course, the
PrinterJob
object in the
actionPerformed()
method code has no way of knowing how
many pages need to be printed. When you call the
PrinterJob
object's
print()
method, it continues call-
ing the
SketcherView
object's
print()
method until the value returned indicates there are no more pages
to be printed. You can return one of two values from the
print()
method in the
Printable
interface —
either
PAGE_EXISTS
, to indicate you have rendered a page, or
NO_SUCH_PAGE
when there are no more pages
to be printed. Both constants are defined in the
Printable
interface. The
PrinterJob
object continues call-
ing the
print()
method for the
Printable
object until the method returns the value
NO_SUCH_PAGE
. If you
don't make sure that the
print()
method returns this value at some point, you have an indefinite loop in the
program.
Three arguments are passed to the
print()
method in the
Printable
interface. The first is the graphics
context that you must use to write to the printer. The reference is to an object of type
Graphics2D
, so you
typically cast it to this type before using it — just as you did within the
paint()
method for a component.
In the
print()
method in the view class, you could draw the sketch on the printer with the following state-
ments:
public int print(Graphics g, // Graphics context for printing
PageFormat pageFormat, // The page format
int pageIndex) // Index number of current page
throws PrinterException {
Graphics2D g2D = (Graphics2D) g;
paint(g2D);
return PAGE_EXISTS;
}
This works after a fashion, but you have more work to do before you can try this out. At the moment, it
prints the same page over and over, indefinitely, so let's take care of that as a matter of urgency!