Java Reference
In-Depth Information
// Print the window
public int print(Graphics g,
PageFormat pageFormat,
int pageIndex)
throws PrinterException {
if(pageIndex>0) // Only one page page 0 to be printed
return NO _ SUCH _ PAGE;
// Scale the component to fit
Graphics2D g2D = (Graphics2D) g;
// Calculate the scale factor to fit the window to the page
double scaleX = pageFormat.getImageableWidth()/getWidth();
double scaleY = pageFormat.getImageableHeight()/getHeight();
double scale = Math.min(scaleX,scaleY); // Get minimum scale factor
// Move paper origin to page printing area corner
g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2D.scale(scale,scale); // Apply the scale factor
print(g2D); // Draw the component
return PAGE _ EXISTS;
}
Make sure you have the necessary additional imports:
import javax.print.PrintService;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
If you recompile and run Sketcher once more, the F ile | Print window menu item should be operational.
How It Works
The menu operation and the printing mechanism are as we have already discussed. The SketchFrame
object is the page painter for the window so the print() method is where it all happens. After
checking the page index value and casting the Graphics reference passed to the method to
Graphics2D , we calculate the scaling factor to fit the window to the page. The getWidth() and
getHeight() methods inherited in our SketchFrame class return the width and height of the
window respectively. We then apply the scale just as we did for printing a sketch. The coordinates of the
top left corner of the window are at (0,0) so we can just print it once we have applied the scaling factor.
Calling the inherited print() method with g2D as the argument does this.
I'm sure you will have noticed that the output has deficiencies. The title bar and window boundary are
missing. Of course, a JFrame object is a top-level window, and since it is derived from the Frame class
it is a heavyweight component with its appearance determined by its peer, which is outside the Java
code. The print() method for the JFrame object that we call to print the window does not include
the peer created elements of the window. The printAll() method does though. Modify the code in
the print() method to call printAll() rather than print() , like this :
Search WWH ::




Custom Search