Java Reference
In-Depth Information
printJob.setPageable(theApp.getView()); // The view is the page source
if(printJob.printDialog()) { // Display print dialog
// If true is returned...
try {
printJob.print(); // then print
} catch(PrinterException pe) {
System.out.println(pe);
JOptionPane.showMessageDialog(SketchFrame.this,
"Error printing a sketch.",
"Printer Error",
JOptionPane.ERROR
_
MESSAGE);
}
}
This code is the earlier version that uses the
printDialog()
method without an argument to show the
effect in this context. If you comment out the most recent code, you can try both versions by juggling
the commented out code. On my system, the print dialog now shows the correct number of pages to be
printed, courtesy of the
Pageable
interface implementation that we added to Sketcher.
How It Works
The
PrinterJob
object now calls methods in the
Pageable
interface that we have implemented for
the view. The number of pages in the document is now determined by our
getNumberOfPages()
method, and the
PageFormat
and
Printable
objects are now obtained individually for each page.
If you switch the code back to using the
printDialog()
and
print()
methods with an argument of
type
PrintRequestAttributeSet
, the print operation will run in the same way. The print attributes
passed to the
print()
method will not override those specified in the
PageFormat
object returned by
the
getPageFormat()
method for the
Pageable
object. If the attribute set passed to the print
method includes attributes not determined by the
Pageable
object - such as a
Copies
attribute
object - these will have an effect on the printing process.