Java Reference
In-Depth Information
You can see that there are three arguments passed to the
print()
method in the
Printable
interface. The first is the graphics context that you must use to write to the printer. The reference passed
to the method is actually of type
Graphics2D
, so you will typically cast it to this type before using it -
just as we did within the
paint()
method for a component to draw on the screen. In the
print()
method in our view class, we could draw the sketch on the printer with the statements:
public int print(Graphics g, // Graphics context for printing
PageFormat pageFormat, // The page format
int pageIndex) // Index number of current page
throws PrinterException {
Graphics2D g2D = (Graphics2D) g;
paint(g2D);
return PAGE
_
EXISTS;
}
This will work after a fashion, but we have more work to do before we can try this out. At the moment,
it will print the same page over and over, indefinitely, so let's take care of that as a matter of urgency!
It's the third argument that carries an index value for the page. The first page in a print job will have
index value 0, the second will have index value 1, and so on for as long as there are more pages to be
printed. If we intend to print our sketch on a single page, we can stop the printing process by checking
the page index:
public int print(Graphics g, // Graphics context for printing
PageFormat pageFormat, // The page format
int pageIndex) // Index number of current page
throws PrinterException {
if(pageIndex>0)
return NO
_
SUCH
_
PAGE;
Graphics2D g2D = (Graphics2D) g;
paint(g2D); // Draw the sketch
return PAGE
_
EXISTS;
}
We only want to print one page, so if the value passed as the third parameter is greater than 0, we
return
NO
_
SUCH
_
PAGE
to stop the printing process.
While at least we won't now print endlessly, we still won't get an output formatted the way we want it.
We must look into how we can use the information provided by the second argument that is passed to
the
print()
method, the
PageFormat
object, to position the output properly.
The PageFormat Class
The
PageFormat
reference that is passed to the
print()
method for a page provides details of the page
size, the position and size of the printable area on the page, and the orientation - portrait or landscape.