Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

13. Graphics and Sound > 13.11. Printing in Java

13.11. Printing in Java


You need to generate hardcopy.


Use java.awt.print.PrinterJob.


The JDK 1.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 is sent to that printer (if there isn’t a default printer, I don’t know what happens). Unlike the 1.1 Printing API, however, Java is in charge of what to print and in what order, although 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 Recipe 9.7). In this example, we pass an anonymous inner class (see Recipe 9.6); this is not required, but as usual, it 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 efficient because if the user wants to print only page 57, you get called only once to print that page. Note that the official documentation calls the third argument a pageIndex, but it’s really a page number. Trust me. Presumably it’s called a pageIndex to remind you that in some printing jobs (such as this book), there are unnumbered pages and pages with those funny little roman numerals at the front (see Recipe 5.11).


You are currently reading a PREVIEW of this book.


Get instant access to over $1 million worth of books and videos.


Start a Free 10-Day Trial

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint