Java Reference
In-Depth Information
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;
}
Directory "Sketcher 13 printing the application window"
The
getWidth()
and
getHeight()
methods you are calling here are inherited in the
SketcherFrame
class from the
Component
class, and they return the width and height of the window, respectively.
If you recompile and run Sketcher once more, the File
⇒
Print Window menu item should be operational.
How It Works
The menu operation and the printing mechanism function as I have already discussed. The
Sketcher-
Frame
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
,
you calculate the scaling factor to fit the window to the page. The
getWidth()
and
getHeight()
meth-
ods inherited in our
SketcherFrame
class return the width and height of the window, respectively. You
then apply the scale just as you did for printing a sketch. The coordinates of the top-left corner of the
window are at (0, 0) so you can just print it once you have applied the scaling factor. Calling the inherited
print()
method with
g2D
as the argument does this.
I'm sure you have noticed that the output has deficiencies. The title bar and window boundary are miss-
ing. Of course, a
JFrame
object is a top-level window, and because it is derived from the
Frame
class, it
is a heavyweight component with its appearance determined by its native peer, which is outside the Java
code. The
print()
method for the
JFrame
object that you call to print the window does not include the
peer elements of the window (peer elements are the native GUI elements). The
printAll()
method that
the
JFrame
class inherits from the
Component
class does though. Modify the code in the
print()
method
in
SketcherFrame
to call
printAll()
rather than
print()
, like this: