CONTENTS | PREV | NEXT Java 2D API


1.3 Text

The Java 2D API provides text handling support that ranges from the simple use of fonts to professional-quality management of character layout and font features.

The Java 2D API enhanced Font class provides greater control over fonts than the existing java.awt.Font class. It also allows you to retrieve more information about a font, such as the Beziér paths of individual character glyphs. The Java 2D API Font class will supersede java.awt.Font.


1.3.1 Drawing Text

To draw text, you use the same process that you use for paths. Instead of using a GeneralPath object to define a shape, you create a Font object and render the text by calling Graphics2D.drawString.

For example, to draw a large letter `J', rotated 45° counterclockwise, on top of the rectangles from the previous example, you add the following code to the body of the paint method:

// get a 200 point version of Helvetica-BoldOblique
Font myFont = new Font("Helvetica-BoldOblique", 
                       Font.PLAIN, 200);
// display the character `J' in green 
// the rotation and translation have already been done
g2d.setColor(Color.green);
// the J is rendered opaque, so reset the composite.
g2d.setComposite(AlphaComposite.
getInstance(AlphaComposite.SRC_OVER, 1.0f));
// Draw the J
g2d.drawString("J", 0f, 20f);
Because the Java 2D API Font class provides a getGlyphOutline method1 that returns the character path, you can use a text string as a clipping path. For example, you could draw only those parts of the rectangles that would show through the rotated letter J by using the character path, scaled appropriately, as a clipping path:

Figure 1-4 Using Text as a Clipping Path

To do this, you get the character's shape by calling getGlyphOutline, which returns an instance of Shape. You then supply the Shape object as an argument to setClip, a method defined by Graphics2D. In Figure 1-4, the text outline is also stroked in black.

As illustrated by these examples, the Java 2D API treats text as a first-class citizen. It can be drawn, transformed, used as a clipping path, and composited just like any other graphic element. You can even perform hit detection on text with the Graphics2D.hitString method.



CONTENTS | PREV | NEXT
Copyright © 1997 Sun Microsystems, Inc. All Rights Reserved.