|
The first step in drawing text involves choosing the font for the text.
You can use the default or specify which of fonts you desire.
The Font and
FontMetrics
classes are described in the Chapter
6: Java: Text Draw section. Below is an Applet
that performs the same text drawing as that of the JApplet
version in that section.
|
import
java.applet.*;
import java.awt.*;
/** Demonstration of text drawing in AWT. **/
public class TextApplet extends
Applet
{
public
void paint (Graphics g )
{
String
msg = "Set text in center";
// Set the context color for
lines and text
g.setColor (Color.red);
// Create the font and pass
it to the Graphics context
g.setFont (new
Font ("Monospaced",Font.PLAIN,24));
// Get measures needed to center
the message
FontMetrics fm = g.getFontMetrics
();
// How many pixels wide is the
string
int msgWidth = fm.stringWidth
(msg);
// How far above the baseline
can the font go?
int ascent = fm.getMaxAscent
();
// How far below the baseline?
int descent= fm.getMaxDescent
();
// Use the string width to find
the starting point
int msgX = getSize ().width/2
- msgWidth/2;
// Use the vertical height of
this font to find
// the vertical starting coordinate
int msgY = getSize ().height/2
- descent/2 + ascent/2;
g.drawString (msg,msgX,msgY);
}
// paint
} // class TextApplet
|
Here we create a Font
object for the Monospace
type with the given style and size. Then we pass it to the graphics
context. We then obtain from the graphics context a FontMetrics
object for the current font setting.
With the FontMetrics
object we then obtain the stringwidth and the vertical dimensions neccessary
to calculate where to draw the string. Note that the drawString
method uses the horizontal and vertical coordinates passed in the arguments
for the left baseline point of the string.
Latest update: Oct. 27, 2004
|
|