Java Reference
In-Depth Information
case TEXT:
text = "TEXT";
break;
default:
assert false;
}
typePane.setText(text); // Set the pane text
}
Directory "Sketcher 4 creating text elements"
This code is analogous to that of the other types. All that is necessary is to set the
typePane
to display
"TEXT"
. You can define the class for a text element next. Then you are able to complete the mechanism for
adding text elements to a sketch.
Defining the Text Class
You can use the
drawString()
method for the
Graphics2D
object to display text on a sketch. You have to
figure out the bounding rectangle for a text element that you use when you want it redrawn. With
Shape
objects, you can use the
getBounds()
method supplied by the 2D shape classes in
java.awt.geom
to obtain
a bounding rectangle, but for text you have to do a bit more work.
The bounding rectangle for a text string is dependent on the length of the string, the font used in a given
graphics context, and the characters in the string, because some characters are wider and higher than oth-
ers. You therefore need a
Graphics2D
object, the string, and the font used to display the string available
to get the bounding rectangle. A
java.awt.FontMetrics
object can help you get the bounding rectangle,
and calling
getFontMetrics()
for a
Graphics2D
object with a
Font
object as the argument provides one.
The
stringWidth()
method for the
FontMetrics
object provides an estimate of the width of the bounding
rectangle and the
getHeight()
method provides an estimate of the height. The estimates for the width and
height are not totally accurate, so it's a good idea to increase these a little to ensure the text is completely
inside the rectangle.
Here's the definition for the inner
Text
class in
Element
:
public static class Text extends Element {
public Text(String text, Point start, Color color, FontMetrics fm) {
super(start, color);
this.text = text;
this.font = fm.getFont();
maxAscent = fm.getMaxAscent();
bounds = new java.awt.Rectangle(position.x, position.y,
fm.stringWidth(text) + 4, maxAscent+ fm.getMaxDescent() + 4);
System.out.println(bounds);
}
public void draw(Graphics2D g2D) {
g2D.setPaint(highlighted ? HIGHLIGHT_COLOR : color);
Font oldFont = g2D.getFont();
// Save the old font