Java Reference
In-Depth Information
Starting the Printing Process
Let's use what we now know about printing to add some code to the
actionPerformed()
method in the
FileAction
class. This will handle the event for the
printAction
object in the
SketchFrame
class:
if(name.equals(printAction.getValue(NAME))) {
// Get a printing object
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService printer = printJob.getPrintService();
if(printer == null) {
JOptionPane.showMessageDialog(SketchFrame.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
// 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);
}
}
}
The code here obtains a
PrinterJob
object and, after verifying that we do have a printer to print on,
sets the view as the printable source. The expression for the second
if
will display a print dialog, and if
the return value from the
printDialog()
method call is
true
, we call the
print()
method for the
printJob
object to start the printing process. This is one of two overloaded
print()
methods defined
in the
PrinterJob
class. We will look into the other one when we try out the alternative
printDialog()
method.
You will need to add three more
import
statements to the
SketchFrame.java
file:
import javax.print.PrintService;
import java.awt.print.PrinterJob;
import java.awt.print.PrinterException;
The
SketchFrame
class still won't compile at the moment, as we haven't made the
SketchView
class
implement the
Printable
interface yet.