Printing: Java 2
Problem
You need to generate hardcopy, and you’re using Java 2.
Solution
Use java.awt.print.PrinterJob
.
Discussion
Like its predecessor, the Java 2 printing API makes you divide the
data into pages. Again, you start by getting a
PrinterJob
object to control your printing.
You’ll usually want to let the user pick a printer, which you
do by calling the PrinterJob
’s method
printerDialog( )
. This pops up a platform-specific
print chooser dialog, and if the user picks a printer, you get back a
PrinterJob
object (otherwise, again, you get back
null). If you don’t call printerDialog( )
and there is a default printer, your job will be sent to that printer
(if there isn’t a default printer, I don’t know what
happens). Unlike the 1.1 API, however, Java is in charge of what to
print and in what order, though your program is still responsible for
pagination and drawing each page onto a print buffer. You need to
provide an object that implements the
Printable
interface (see Section 8.8). In this example, we pass an anonymous inner
class (see Section 8.7); this is not required but as
usual makes the code more succinct by eliminating having to write
another class in another file and by keeping the action and the
result together. Java calls this object’s print( )
method once for each page the user has requested. This is more efficient than the 1.1 method, since if the user wants to print only page 57, you only get called once to print that page (in 1.1, you’d have to generate ...
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.