Java Reference
In-Depth Information
"Error printing a sketch.",
"Printer Error",
JOptionPane.ERROR_MESSAGE);
}
}
} else if(this == exitAction) {
checkForSave();
System.exit(0);
}
Directory "Sketcher 6 printing a sketch"
The code here obtains a
PrinterJob
object and, after verifying that there is a printer to print on, sets the
view as the printable source. You don't need access to the
PrinterService
object to print, but it's one way
of verifying that a printer is available. The expression for the second
if
displays a print dialog, and if the
return value from the
printDialog()
method call is
true
, you call the
print()
method for the
printJob
object to start the printing process. This is one of two overloaded
print()
methods that the
PrinterJob
class defines. You look into the other one when you try out the alternative
printDialog()
method a little
later in this chapter.
Two more
import
statements are needed in the
SketcherFrame.java
file:
import javax.print.PrintService;
import java.awt.print.*;
The
SketcherFrame
class still doesn't compile at the moment because you haven't made the
Sketcher-
View
class implement the
Printable
interface yet.
Printing Pages
The object that you pass to the
setPrintable()
method is responsible for all the details of the printing pro-
cess. The object class type must implement the
Printable
interface, which implies defining the
print()
method in the class. You can make the
SketcherView
class implement the
Printable
interface like this:
// Import statements as before...
import java.awt.print.*;
class SketcherView extends JComponent implements Observer, Printable {
// Constructor code etc. as before...
// Print the sketch on a local printer
public int print(Graphics g,
// Graphics context for printing
PageFormat pageFormat,
// The page format
int pageIndex)
// Index number of current page
throws PrinterException {
// Code to do the printing...
}
// Rest of the class definition as before...
}