Java Reference
In-Depth Information
The third argument to print() is an index value for the page. The first page in a print job has index value
0, the second has index value 1, and so on for as long as there are more pages to be printed. If you intend to
print a sketch on a single page, you can stop the printing process by checking the page index:
public int print(Graphics g, // Graphics context for printing
PageFormat pageFormat, // The page format
int pageIndex) // Index number of current page
throws PrinterException {
if(pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2D = (Graphics2D) g;
paint(g2D); // Draw the sketch
return PAGE_EXISTS;
}
You want to print only one page, so if the value passed as the third parameter is greater than 0, you return
NO_SUCH_PAGE to stop the printing process.
Although you won't now print endlessly, you still won't get the output formatted the way you want it.
You must use the information provided by the second argument that is passed to the print() method, the
PageFormat object, to position the sketch properly on the paper.
The PageFormat Class
The PageFormat reference that is passed as the second argument to the print() method provides details
of the page size, the position and size of the printable area on the page, and the orientation — portrait or
landscape.
Perhaps the most important pieces of information is where the top-left corner of the printable area (or im-
ageable area to use the terminology of the method names) is on the page and its width and height, because
this is the area you have available for printing your output. The printable area on a page is simply the area
within the current margins that are defined for your printer. The position of the printable area is returned
by the methods getImageableX() and getImageableY() . These return the x and y coordinates of the top-
left corner of the printable area in user coordinates for the printing context as values of type double , which
happen to be in units of 1/72 of an inch, which, as luck would have it, corresponds to a point — as in point
size for a font. The width and height of the printable area are returned in the same units by the getImage-
ableWidth() and getImageableHeight() methods for the PageFormat object.
The origin of the page coordinate system, the point (0,0), corresponds initially to the top-left corner of
the paper. If you want the output to be placed in the printable area on the page, the first step is to move the
origin of the graphics context that you use for writing to the printer to the position of the top-left corner of
the printable area. Figure 21-5 illustrates the way you do this.
FIGURE 21-5
 
 
Search WWH ::




Custom Search