Java Reference
In-Depth Information
Printing Pages
The class object that you pass to the setPrintable() method is responsible for all the detail of the
printing process. This class must implement the Printable interface, which implies defining the
print() method in the same class. We can make the SketchView class implement the Printable
interface like this:
import javax.swing.*; // For various Swing components
import java.awt.*;
import java.util.*; // For Observer, Observer, Iterator
import java.awt.event.*; // For events
import javax.swing.event.MouseInputAdapter;
import java.awt.geom.Line2D;
import java.awt.print.*;
class SketchView extends JComponent
implements Observer, Constants, ActionListener,
Printable {
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...
}
The import statements here have been changed to import all the names in a package where this
significantly reduces the number of lines required. The PrinterJob object will call the print()
method here for each page to be printed. This process starts when you call the print() method for the
PrinterJob object that has overall control of the printing process. You can see that our print()
method can throw an exception of type PrinterException . If you identify a problem within your
print() method code, the way to signal the problem to the PrinterJob object is to throw an
exception of this type.
One point to keep in mind - you should not assume that the PrinterJob object will call the print()
method for your Printable object just once per page. In general the print() method is likely to be
called several times for each page as the output destined for the printer is buffered within the Java
printing system and the buffer will not necessarily be large enough to hold a complete page. You don't
need to worry about this unduly. Just don't build any assumptions into your code about how often
print() is called for a given page.
Of course, our PrinterJob object in the actionPerformed() method code has no way of knowing
how many pages need to be printed. When we call the PrinterJob object's print() method, it will
continue calling the SketchView object's print() method until the value returned indicates there are
no more pages to be printed. You can return one of two values from the print() method in the
Printable interface - PAGE _ EXISTS to indicate you have rendered a page, or NO _ SUCH _ PAGE if
there are no more pages to be printed. Both of these constants are defined in the Printable interface.
The PrinterJob object will continue calling print() until the NO _ SUCH _ PAGE value is returned.
Search WWH ::




Custom Search