Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

Printing

Earlier in this chapter, we hinted at the possibility that you could draw the same stuff on the screen and the printer. It’s true; all you really need to do is get a Graphics2D object that represents a printer rather than an area of the screen. Java’s printing API provides the necessary plumbing. There isn’t room here to describe the whole Printing API, but we will provide you with a short example that will let you get your feet wet (and your paper flowing).

The printing classes are tucked away in the java.awt.print package. You can print anything that implements the Printable interface. This interface has only one method—you guessed it, print()—which is like the paint() methods we’ve already worked with. It accepts a Graphics object that represents the drawing surface of the printer’s page. It also accepts a PageFormat object that encapsulates information about the paper on which you’re printing. Finally, print() is passed the number of the page that is being rendered. All Swing components implement a print() method, which you can use or override to customize their printed appearance.

Your print() implementation should either render the requested page or state that it doesn’t exist. You can do this by returning special values from print(), either Printable.PAGE_EXISTS or Printable.NO_SUCH_PAGE.

You can control a print job, including showing print and page setup dialogs, using the PrinterJob class. The following class enables you to get something on paper. In this example, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content