Java Reference
In-Depth Information
Example 12−2: ScribblePrinter2.java (continued)
// Display the print dialog that allows the user to set options.
// The method returns false if the user cancelled the print request
if (job.printDialog()) {
// If not cancelled, start printing! This will call the print()
// method defined by the Printable interface.
try { job.print(); }
catch (PrinterException e) { System.err.println(e); }
}
}
/**
* This is the method defined by the Printable interface. It prints the
* scribble to the specified Graphics object, respecting the paper size
* and margins specified by the PageFormat. If the specified page number
* is not page 0, it returns a code saying that printing is complete. The
* method must be prepared to be called multiple times per printing request
**/
public int print(Graphics g, PageFormat format, int pagenum) {
// We are only one page long; reject any other page numbers
if (pagenum > 0) return Printable.NO_SUCH_PAGE;
// The Java 1.2 printing API passes us a Graphics object, but we
// can always cast it to a Graphics2D object
Graphics2D g2 = (Graphics2D) g;
// Translate to accommodate the requested top and left margins.
g2.translate(format.getImageableX(), format.getImageableY());
// Figure out how big the drawing is, and how big the page
// (excluding margins) is
Dimension size = this.getSize(); // Scribble size
double pageWidth = format.getImageableWidth(); // Page width
double pageHeight = format.getImageableHeight(); // Page height
// If the scribble is too wide or tall for the page, scale it down
if (size.width > pageWidth) {
double factor = pageWidth/size.width; // How much to scale
g2.scale(factor, factor);
// Adjust coordinate system
pageWidth /= factor;
// Adjust page size up
pageHeight /= factor;
}
if (size.height > pageHeight) { // Do the same thing for height
double factor = pageHeight/size.height;
g2.scale(factor, factor);
pageWidth /= factor;
pageHeight /= factor;
}
// Now we know the scribble will fit on the page. Center it by
// translating as necessary.
g2.translate((pageWidth-size.width)/2,(pageHeight-size.height)/2);
// Draw a line around the outside of the drawing area
g2.drawRect(-1, -1, size.width+2, size.height+2);
// Set a clipping region so the scribbles don't go out of bounds
g2.setClip(0, 0, size.width, size.height);
Search WWH ::




Custom Search