Java Reference
In-Depth Information
We now want to change the print() method implementation in SketchView just to draw the page
with the PageFormat object it is given. Here's the modified print() method. Although we have seen
all this code previously, you should check it carefully as some of the original code we have been adding
as we went along has now been removed:
public int print(Graphics g,
PageFormat pageFormat,
int pageIndex)
throws PrinterException {
if(pageIndex != 1) // Cover page is page 0, this is page 1
return NO _ SUCH _ PAGE;
Graphics2D g2D = (Graphics2D) g;
// Get sketch bounds
Rectangle rect = theApp.getModel().getModelExtent(); // Get sketch bounds
// Calculate the scale to fit sketch to page
double scaleX = pageFormat.getImageableWidth()/rect.width;
double scaleY = pageFormat.getImageableHeight()/rect.height;
double scale = Math.min(scaleX,scaleY); // Get minimum scale factor
// Move origin to page printing area corner
g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2D.scale(scale,scale); // Apply scale factor
g2D.translate(-rect.x, -rect.y); // Move top left to the origin
paint(g2D); // Draw the sketch
return PAGE _ EXISTS;
}
It works much as before - the code dealing with the page orientation has been removed, and we only
print when the page index is 1. The orientation of the page is taken care of automatically because the
PageFormat object is set up before this method is called. The Graphics object that is passed to
print() will reflect the orientation specified in the PageFormat object.
The last thing we need to do is alter the code in the actionPerformed() method for the inner class
FileAction in SketchFrame . We must replace the setPrintable() method call with a
setPageable() call:
if(name.equals(printAction.getValue(NAME))) {
// Get a printing object
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService printer = printJob.getPrintService();
if(printer == null) { JOptionPane.showMessageDialog(SketchFrame.this,
"No default printer available.",
"Printer Error",
JOptionPane.ERROR _ MESSAGE);
return;
}
Search WWH ::




Custom Search