13.2. Controlling Printing

The PrinterJob class is the boss of the printing process. As you've seen, you can obtain an instance of PrinterJob with the following factory method:

public static PrinterJob getPrinterJob()

This method returns a PrinterJob instance. You can use this PrinterJob to show a print dialog and a page setup dialog, and to start and cancel a print job.

13.2.1. PrinterJob Basics

There are two essential steps to using a PrinterJob. You have to give it something to print, and you have to tell it to start printing.

The "something to print" may be a Printable, as you saw in the examples above:

public abstract void setPrintable(Printable painter)

This method sets this PrinterJob to print the supplied object.

public abstract void setPrintable(Printable painter, PageFormat format)

Use this method to supply a Printable and an associated PageFormat to the PrinterJob.

PrinterJob also knows how to print instances of Printable's more capable cousin, java.awt.print.Pageable. But don't be confused — Pageable is really just a container for Printable objects anyhow. I'll talk about the Pageable interface later in this chapter. This method gives a PrinterJob a Pageable object to print:

public abstract void setPageable(Pageable document)

This method tells this PrinterJob to print the supplied Pageable.

Once the PrinterJob knows what it's supposed to print, you just need to kick off the job:

public abstract void print() throws PrinterException

This method begins the printer ...

Get Java 2D Graphics 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.