Java Reference
In-Depth Information
FontMetrics class provides various methods to obtain various measurements
of characters and strings:
getHeight () - total line height
getMaxAscent () - height above the baseline
getMaxDescent () - total
stringWidth () - width of a string
Such information helps to position strings according to their size. The following
class, DrawTextPanel ,which we can display with an applet as usual, illus-
trates the basics of drawing a string according to its size specifications (see
Figure 6.7(b)). It creates a Font object for the Monospaced type in the plain
style and a 24-point size. After this Font is set as the current font for the graphics
context, the FontMetrics object is obtained from the context. It provides var-
ious measurements of the characters, and these measurements are used to center
the string.
import javax.swing.*;
import java.awt.*;
/** JPanel subclass to demonstrate a drawing text. **/
public class DrawTextPanel extends JPanel
{
public void paintComponent (Graphics g) {
// First paint background
super.paintComponent (g);
// Add your drawing instructions here
g.setColor (Color.red);
String msg ="Set text in center";
// Create the font and pass it to the Graphics context
g.setFont (new Font ("Monospaced", Font.BOLD, 24));
// Get measures needed to center the message
FontMetrics fm = g.getFontMetrics ();
// How many pixels wide is the string
int msg - width = 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 ();
 
Search WWH ::




Custom Search