Java Reference
In-Depth Information
without arguments displays the native dialog if the
PrinterJob
object is printing on a native printer, so I'm
introducing that first and return to the other version later.
If the print dialog is closed using the button that indicates printing should proceed, the
printDialog()
method returns
true
; otherwise, it returns
false
. The method throws a
java.awt.HeadlessException
if there is no display attached to the system. Thus, to initiate printing, you can call the
printDialog()
method to put the decision to proceed in the hands of the user, and if the method returns
true
, call the
print()
method for the
PrinterJob
object to start printing. Note that the
print()
method throws a
java.awt.print.PrinterException
if an error in the printing system causes the operation to be aborted.
Of course, the
PrinterJob
object has no prior knowledge of what you want to print, so you have to call a
method to tell the
PrinterJob
object where the printed pages are coming from before you initiate printing.
The simplest way to do this is to pass a reference to an object of a class that implements the
Printable
interface to the
setPrintable()
method.
In Sketcher, the obvious candidate to print a sketch is the
SketcherView
object, and you could provide
for the possibility of sketches being printed by making the
SketcherView
class implement the
Printable
interface. You could then set the source of the printed output by passing a reference to the view to the
setPrintable()
method for a
PrinterJob
object. You might consider the
SketcherModel
object to be a
candidate to do the printing, but printing is really no more related to a sketch than plotting it or displaying
it on the screen. The model is the input to the printing process, not the owner of it. It is generally better to
keep the model dedicated to encapsulating the data that represents the sketch.
Starting the Printing Process
You can use what you now know about printing to add some code to the
actionPerformed()
method in the
FileAction
inner class to
SketcherFrame
. This handles the event for the
printAction
object:
if(this == printAction) {
// Get a printing object
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService printer = printJob.getPrintService();
if(printer == null) { // See if there is a printer
JOptionPane.showMessageDialog(SketcherFrame.this,
"No default printer available.",
"Printer Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// The view is the page source
printJob.setPrintable(theApp.getView());
if(printJob.printDialog()) {
// Display print dialog
try {
// and if true is returned...
printJob.print();
// ...then print
} catch(PrinterException pe) {
System.out.println(pe);
JOptionPane.showMessageDialog(SketcherFrame.this,