Printing: JDK 1.1
Problem
You need to generate hardcopy, and you’re using JDK 1.1.
Solution
Use java.awt.PrintJob
. Or, upgrade to JDK 1.2.
Discussion
The JDK 1.1 API puts your program in the driver’s seat: you
decide what to print and when to print it. But first, you have to let
the user pick a printer, which you can do by calling the
Toolkit method getPrinterJob( )
. This pops up a platform-specific print chooser dialog,
and if the user picks a printer, you get back a
PrintJob
object (otherwise you get back null).
Your program is in charge of
pagination (breaking the data into pages)
and drawing each page onto a print buffer. How? For each page you
want to print, call the
PrintJob
’s getGraphics( )
method to retrieve a Graphics
object.
Use it as you will; any of its draw or fill methods will draw, not to
the screen, but onto paper. Your best bet is to pass it to your
paint( )
method, if you have one. This is one of the few places where you do
call paint( )
directly. When the page is done,
call the Graphics
object’s dispose( )
method. When the whole print job is
done, call the PrintJob
’s end( )
method, and you’re
finished -- the data is on its way to the printer.
Here’s a little program that displays a simple graphical
component called a DemoGFXCanvas
.
When you click the Print button at the
bottom, the program prints the contents of the
DemoGFXCanvas
(this is shown graphically in Figure 12-6). When you click on the Print button in the main window, the printer dialog shown at ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.