Java Reference
In-Depth Information
if(pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2D = (Graphics2D) g;
float x = (float)pageFormat.getImageableX();
float y = (float)pageFormat.getImageableY();
GeneralPath path = new GeneralPath();
path.moveTo(x+1, y+1);
path.lineTo(x+(float)pageFormat.getImageableWidth()-1, y+1);
path.lineTo(x+(float)pageFormat.getImageableWidth()-1,
y+(float)pageFormat.getImageableHeight()-1);
path.lineTo(x+1, y+(float)pageFormat.getImageableHeight()-1);
path.closePath();
g2D.setPaint(Color.red);
g2D.draw(path);
// Get a 12 pt bold version of the default font
Font font = g2D.getFont().deriveFont(12.f).deriveFont(Font.BOLD);
g2D.setFont(font);
// Set the new font
Rectangle2D textRect =
new TextLayout(sketchName, font,
g2D.getFontRenderContext()).getBounds();
double centerX = pageFormat.getWidth()/2;
double centerY = pageFormat.getHeight()/2;
Rectangle2D.Double surround = new Rectangle2D.Double(
centerX-textRect.getWidth(),
centerY-textRect.getHeight(),
2*textRect.getWidth(),
2*textRect.getHeight());
g2D.draw(surround);
// Draw text in the middle of the printable area
g2D.setPaint(Color.blue);
g2D.drawString(sketchName, (float)(centerX-textRect.getWidth()/2),
(float)(centerY+textRect.getHeight()/
2));
return PAGE_EXISTS;
}
Directory "Sketcher 12 using the Pageable interface"
To center the file name on the page, you need to know the width and height of the text string when it
is printed. The getStringBounds() method in the Font class returns the rectangle bounding the string.
The second argument is a reference to an object of type FontRenderContext that the getFontRender-
Context() method for g2D returns. A FontRenderContext object contains all the information the
getStringBounds() method needs to figure out the rectangle bounding the text when it is printed. This
Search WWH ::




Custom Search