Java Reference
In-Depth Information
The solution is to implement the
Pageable
interface in a class, and call the
setPageable()
method
for the
PrinterJob
object instead of
setPrintable()
. The essential difference between the
Printable
and
Pageable
interfaces is that a
Printable
object encapsulates a single page to be
printed whereas a
Pageable
object encapsulates multiple pages. Each of the pages to be printed by a
Pageable
object is encapsulated by a
Printable
object though.
Implementing the Pageable Interface
A class that implements the
Pageable
interface defines a set of pages to be printed. A
Pageable
object must be able to supply the
PrinterJob
object a count of the number of pages for a job, a
reference of type
Printable
for the object that is to print each page, plus a
PageFormat
object
defining the format of each page. The
PrinterJob
acquires this information by calling the three
methods declared in the
Pageable
interface:
Method
Description
getNumberOfPages()
Must return an
int
value specifying the number of
pages to be printed. If the number of pages cannot
be determined then the value
UNKNOWN
_
NUMBER
_
OF
_
PAGES
can be returned.
This value is defined in the
Pageable
interface.
getPageFormat(int pageIndex)
This method must return a
PageFormat
object for
the page specified by the page index that is passed
to it.
getPrintable(int pageIndex)
This method must return a reference of type
Printable
to the object responsible for printing
the page specified by the page index that is passed
to it.
At the start of a print job the
PrinterJob
object will call the
getNumberOfPages()
method to
determine how many pages are to be printed. If you return the value
UNKNOWN
_
NUMBER
_
OF
_
PAGES
then the process relies on a
Printable
object returning
NO
_
SUCH
_
PAGE
at some point to stop
printing. It is therefore a good idea to supply the number of pages when it can be determined.
For each page index, the
PrinterJob
object will call the
getPageFormat()
method to obtain the
PageFormat
object to be used, and call the
getPrintable()
method to obtain a reference to the
object that will do the printing. Of course, just because you
can
supply a different
Printable
object for
each page doesn't mean that you
must
. You could use as many or as few as you need for your
application. Remember that the
print()
method for a
Printable
object may be called more than
once by the
PrinterJob
object to print a particular page and the page should be rendered each time,
so you must not code the method in a way that presumes otherwise.