Java Reference
In-Depth Information
g2D.setFont(font); // Set the new font
// Reference point for drawString() is the baseline of the 1st character
g2D.drawString(text, position.x + 2, position.y + maxAscent + 2);
g2D.setFont(oldFont);
// Restore the old font
}
public void modify(Point start, Point last) {
// No code is required here, but you must supply a definition
}
private Font font;
// The font to be used
private int maxAscent;
// Maximum ascent
private String text;
// Text to be displayed
private final static long serialVersionUID = 1001L;
}
Directory "Sketcher 4 creating text elements"
The constructor calls the superclass constructor to store the position and color for the element and then
stores the text string and the font in members of the
Text
class. The font is obtained from the
FontMetrics
object that is passed as the last constructor argument. The
getMaxAscent()
method that the constructor calls
for the
FontMetrics
object returns the maximum ascent, and this is stored in a class member for later use by
the
draw()
method. You create the bounding rectangle in the constructor using information provided by the
FontMetrics
object. The
stringWidth()
method provides the width of the string passed as the argument
and the
getMaxDescent()
method returns the maximum descent for the characters in the font.
The
position
member defines the top-left corner of the enclosing rectangle for the text.
Figure 20-8
il-
lustrates how the rectangle is defined based on information from the
FontMetrics
object.
The coordinates that you supply to the
drawString()
method in the
draw()
method for the
Text
class
specifies the baseline of the first character in the string, so you must add the maximum character ascent to
the
y
coordinate of
position
and add 2 to get this. This is because you increase the overall width and height
of the rectangle by 4 to be sure the text is fully enclosed.