Chapter 13. Printing
and Graphics2D objects represent a
"drawing surface"; in Chapter 12, we saw examples of using both the screen and
an off-screen buffer as drawing surfaces. Printing in Java is simply
a matter of obtaining a Graphics object that uses
a printer as a drawing surface. Once you have a
Graphics object, you can print text and draw
graphics to the printer, just as you do onscreen.
The tricky thing about printing in Java is obtaining the
Graphics object that represents the printer. The
API for doing this keeps changing:
Java 1.1 added the first simple printing API using the
java.awt.PrintJob class. The major weakness of
this API is that it does not support Java 2D graphics.
Java 1.2 defined a more advanced printing API in the new package
java.awt.print. This new API supports Java 2D
graphics, includes a Printable interface, and
provides the ability to explicitly set printing attributes such as
page margins, orientation, and use of color. It also allows print
jobs to be initiated without displaying a Print dialog to the user.
Java 1.3 enhanced the Java 1.1 API by adding the ability to define
printing attributes with the
java.awt.PageAttributes classes. Unfortunately, the API is still
limited to drawing with the basic Graphics object,
and it cannot use the Java 2D graphics methods defined in
Java 1.4 defined a new API in the javax.print
package and subpackages. This new API is interoperable with the Java
1.2 API but is substantially new. It is the most complex API yet,
introducing the ability to select a printer from a list of available
printers based on printer name, capabilities, or location; print to
files instead of printers; track the progress of print jobs with
event listeners; and spool text and image files directly to a printer
without actually drawing them.
As you can tell from this list of API revisions, printing is a
difficult topic, and it is hard to get it right. This applies to
implementations as well as APIs, and you may find that your Java
implementation does not support printing as well as you would like.
While the most common cases typically work, you may run into
difficulties if you push any of these APIs too hard.
This chapter includes examples of each of these printing APIs,
including extended examples of the Java 1.1 and Java 1.4 APIs. It
starts by developing a simple Swing component that displays an image.
Three revisions of this component illustrate each of the three