Java Reference
In-Depth Information
Example 12−4: PrintableDocument.java (continued)
public int print(Graphics g, PageFormat format, int pageIndex) {
// Return an error code on attempts to print past the end of the doc
if (pageIndex >= numPages) return NO_SUCH_PAGE;
// Cast the Graphics object so we can use Java2D operations
Graphics2D g2 = (Graphics2D)g;
// Translate to accommodate the top and left margins
g2.translate(format.getImageableX(), format.getImageableY());
// Scale the page by the specified scaling factor
g2.scale(scalefactor, scalefactor);
// Display a page number centered in the area of the top margin.
// Set a new clipping region so we can draw into the top margin
// But remember the original clipping region so we can restore it
if (pageIndex > 0) {
Shape originalClip = g.getClip();
g.setClip(new Rectangle(0, (int)-printY,
(int)printWidth, (int)printY));
// Compute the header to display, measure it, then display it
String numString = "- " + (pageIndex+1) + " -";
// Get string and font measurements
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D numBounds = headerFont.getStringBounds(numString, frc);
LineMetrics metrics = headerFont.getLineMetrics(numString, frc);
g.setFont(headerFont); // Set the font
g.setColor(Color.black); // Print with black ink
g.drawString(numString, // Display the string
(int)((printWidth-numBounds.getWidth())/2),
(int)(-(printY-numBounds.getHeight())/2 +
metrics.getAscent()));
g.setClip(originalClip); // Restore the clipping region
}
// Get the staring position and length of the page within the document
double pageStart = 0.0, pageLength = printHeight;
if (pageIndex > 0)
pageStart = ((Double)pageOffsets.get(pageIndex-1)).doubleValue();
if (pageIndex < numPages-1)
pageLength = ((Double)pageLengths.get(pageIndex)).doubleValue();
// Scroll so that the appropriate part of the document is lined up
// with the upper-left corner of the page
g2.translate(0.0, -pageStart);
// Now paint the entire document. Because of the clipping region,
// only the desired portion of the document will actually be drawn on
// this sheet of paper.
root.paint(g, drawRect);
// Finally return a success code
return PAGE_EXISTS;
}
/**
* This inner class is a concrete implementation of View, with a
* couple of key method implementations. An instance of this class
Search WWH ::




Custom Search