Java Reference
In-Depth Information
Creating and Using PrinterJob Objects
Because the PrinterJob class encapsulates and manages the printing process for a given physical printer
that is external to the Java Virtual Machine (JVM), you can't create an object of type PrinterJob directly
using a constructor. You obtain a reference to a PrinterJob object for the default printer on a system by
calling the static method getPrinterJob() that is defined in the PrinterJob class:
PrinterJob printJob = PrinterJob.getPrinterJob(); // For the default printer
The printJob object provides the interface to the default printer and controls each print job that you send
to it.
A printer is encapsulated by a javax.print.PrintService object, and you can obtain a reference of
type PrintService to an object encapsulating the printer that is used by a PrinterJob object by calling its
getPrintService() method:
PrintService printer = printJob().getPrintService();
You can query the object that is returned for information about the capabilities of the printer and the kinds
of documents it can print, but I won't divert down that track for the moment. One point you should keep
in mind is that sometimes a printer may not be available on the machine on which your code is running. In
this case the getPrintService() method returns null , so it's a good idea to call the method and test the
reference that is returned, even if you don't want to obtain details of the printer.
If multiple print services are available, such as several printers or perhaps a fax capability, you can obtain
an array of PrintService references for them by calling the static lookupPrintServices() method that
is defined in the PrinterJob class. For example:
PrintService[] printers = PrinterJob.lookupPrintServices();
The printers array has one element for each print service that is available. If no print services are avail-
able, the array has zero length. If you want to select a specific printer for the PrinterJob object to work
with, you just pass the array element corresponding to the print service of your choice to the setPrintSer-
vice() method for the PrinterJob object. For example:
if(printers.length>0) {
printJob.setPrintService(printers[0]);
}
The if statement checks that there are some print services before attempting to set the print service.
Without this you could get an IndexOutOfBoundsException exception if the printers array has no ele-
ments. Of course, more realistically, you would use methods defined in the PrintService interface to query
the printers, and use the results to decide which printer to use.
Displaying a Print Dialog
When you want to provide the user with control over the printing process, you can display a print dialog by
calling the printDialog() method for a PrinterJob object. This method displays the modal dialog that
applies to your particular print facility. There are two versions of the printDialog() method. The version
Search WWH ::




Custom Search