Font Metrics

Font Metrics

Font properties that affect the rendering of strings are represented by the FontMetrics class. You can determine the FontMetrics of the current font in a graphics context with Graphics.getFontMetrics(). If all you want to know is the estimated width of a string in pixels, FontMetrics provides a stringWidth() method for just this purpose. However, a more general method is also provided, called getStringBounds(). This method will return a Rectangle2D instance representing the bounding box of a string when drawn in the given Font. The following program shows how to use this information to draw a rectangle around a string:

 import java.awt.*;import java.awt.event.*;import java.awt.geom.*;public class AWTStringSize extends Frame {  private String __string;  public void paint(Graphics g) {    FontMetrics metrics = g.getFontMetrics();    Rectangle2D rect;    int x, y;    // Get dimensions of string    rect = metrics.getStringBounds(__string, g);    x = (getWidth() - (int)rect.getWidth())/2;    y = (getHeight() - (int)rect.getHeight())/2;    g.drawString(__string, x, y);    // Draw a box slightly outside of the bounds of the string    g.drawRect(x - 1, y - (int)rect.getHeight() - 1,               (int)rect.getWidth() + 2,               (int)rect.getHeight() + 2);                   }  public AWTStringSize(String string) {    __string = string;  }  public static final void main(String[] args) {    AWTStringSize frame;    if(args.length != 1) {      System.err.println("Usage: AWTStringSize string");      return;    }    frame = new AWTStringSize(args[0]);    frame.addWindowListener(new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }      });    frame.setSize(400, 400);    frame.setVisible(true);  }}


Share the Post: