Java Reference
In-Depth Information
Example 11•18: GraphicsExampleFrame.java (continued)
job.setPrintable(new PrintableExample(example));
// Display the print dialog to the user
if (job.printDialog()) {
// If they didn't cancel it, then tell the job to start printing
try {
job.print();
}
catch(PrinterException e) {
System.out.println("Couldn't print: " + e.getMessage());
}
}
}
/**
* This inner class implements the Printable interface in order to print
* a GraphicsExample object.
**/
class PrintableExample implements Printable {
GraphicsExample example; // The example to print
// The constructor. Just remember the example
public PrintableExample(GraphicsExample example) {
this.example = example;
}
/**
* This method is called by the PrinterJob to print the example
**/
public int print(Graphics g, PageFormat pf, int pageIndex) {
// Tell the PrinterJob that there is only one page
if (pageIndex != 0) return NO_SUCH_PAGE;
// The PrinterJob supplies us a Graphics object to draw with.
// Anything drawn with this object will be sent to the printer.
// The Graphics object can safely be cast to a Graphics2D object.
Graphics2D g2 = (Graphics2D)g;
// Translate to skip the left and top margins.
g2.translate(pf.getImageableX(), pf.getImageableY());
// Figure out how big the printable area is, and how big
// the example is.
double pageWidth = pf.getImageableWidth();
double pageHeight = pf.getImageableHeight();
double exampleWidth = example.getWidth();
double exampleHeight = example.getHeight();
// Scale the example if needed
double scalex = 1.0, scaley = 1.0;
if (exampleWidth > pageWidth) scalex = pageWidth/exampleWidth;
if (exampleHeight > pageHeight) scaley = pageHeight/exampleHeight;
double scalefactor = Math.min(scalex, scaley);
if (scalefactor != 1) g2.scale(scalefactor, scalefactor);
// Finally, call the draw() method of the example, passing in
// the Graphics2D object for the printer
example.draw(g2, GraphicsExampleFrame.this);
Search WWH ::




Custom Search