Academic Java    Java Tutorial  >  Applets  >  drawString() using FontMetrics

drawString() using FontMetrics Example

Java drawString() using FontMetrics EXAMPLE output This applet displays some phrases centrally in the drawing surface.

The graphics method setFont() helps to establish the font to be used. But as described in Java documentation this is not always the one hoped for.

The FontMetrics class is used in determining the coordinates of each phrase displayed.
// drawString() using FontMetrics
import java.awt.*;
import javax.swing.*;

class FontMetricsExample extends JApplet {

   public void paint(Graphics g) {
      super.paint(g);
      String[] phrases = {
         "while the cat's away",
         "while the going is good",
         "when all is said and done",
      };

      int width=300, height=300;
      g.setFont(new Font("SansSerif",Font.PLAIN,12));
      FontMetrics fm = g.getFontMetrics();

      int fontHeight = fm.getHeight();
      int y = (height - phrases.length*fontHeight)/2;
      int ygap=5;

      for (int i = 0; i < phrases.length; i++, y+=fontHeight+ygap) {
         int x = width/2 - fm.stringWidth(phrases[i])/2;
         g.drawString(phrases[i],x,y);
      }

   }

}


* drawString() Examples