Java Reference
In-Depth Information
the runtime system will not call
print
again. The programmer has to make
sure that the correct value is returned. This way multi-page documents can be
printed.
Let us now look at a simple implementation of the interface
Printable
.We
implement method
print
such that it prints only one page; our panel is a one-page
document. We first check whether the parameter
pageIndex
is 0 (the first page). If
so we call the
paint
-method of the panel and return
PAGE_EXISTS
.If
pageIndex
is
greater than 0 we return
NO_SUCH_PAGE
. The runtime system will then stop calling
print
.
Let us analyse what is happening in the first case, i.e. when
pageIndex
is 0.
By calling the
paint
-method of the panel, a repainting is initiated. The painting is
done on some device. Which device this is (the screen or the printer) is determined
by the
Graphics
object. In our example we pass the
Graphics
object
g
which we
receive as an argument of
print
on to the
paint
method. This object is generated
by the runtime system and refers to some printer. As a result,
paint
draws to
the printer and not to the screen. We cannot use
repaint
here because it does
not allow a
Graphics
object to be passed as an argument;
repaint
initiates a
redrawing of the screen. The skeleton of the implementation then looks like this:
public int
print(Graphics g, PageFormat pageFormat,
int
pageIndex) {
if
(pageIndex > 0)
{
return
(NO_SUCH_PAGE);
}
else
{
this
.paint(g);
return
(PAGE_EXISTS);
}
}
There are, however, some technical precautions to be taken. First of all one should
switch off the
double buffering
of the graphics. This feature is important for a nice
display when the screen is redrawn but might spoil the printing. After the printing,
the double buffering should be switched on again. We therefore surround the
paint
command by some commands as shown below. We do not elaborate on the class
RepaintManager
used here:
RepaintManager currentManager = RepaintManager.currentManager(
this
);
currentManager.setDoubleBufferingEnabled(
false
);
paint(g);
currentManager.setDoubleBufferingEnabled(
true
);
Another topic to consider when printing is the placement and scaling of the printed
image. The origin of the printer coordinate system is normally the upper left
corner of the
paper
. Most printers, however, cannot print on some small margin
of the paper for technical reasons. Therefore the upper left corner of the
printable
area
of the paper is below and to the right of its upper left corner. The
Graphics
Search WWH ::
Custom Search