Java: Fonts - Centering Text

To find the size of text

For graphical output it's sometimes necessary to know how much vertical and horizontal space text actually uses. To find the size of a font or of a particular String, get a FontMetrics object with a call to getFontMetrics on either a Component, Graphics, or Toolkit object. See below.

Centering Text

From a FontMetrics object for the the current graphics context (eg, the screen or printer) and the current font the width, height, and other distances can be obtained.
// Find the size of string s in font f in the current Graphics context g.
FontMetrics fm   = g.getFontMetrics(f);
java.awt.geom.Rectangle2D rect = fm.getStringBounds(s, g);

int textHeight = (int)(rect.getHeight()); 
int textWidth  = (int)(rect.getWidth());
int panelHeight= this.getHeight();
int panelWidth = this.getWidth();

// Center text horizontally and vertically
int x = (panelWidth  - textWidth)  / 2;
int y = (panelHeight - textHeight) / 2  + fm.getAscent();

g.drawString(s, x, y);  // Draw the string.

Obsolete Fonts and Methods

In Java 1.0 the following names were used: Courier instead of Monospaced, Helvetica instead of SansSerif, and TimesRoman instead of Serif. The Java 1.0 names are traditional type fonts for Latin characters, but don't apply to other writing systems (eg, Chinese, Thai, etc). The new names (Monospaced, SansSerif, Serif) should be used because they can be applied to other writing systems. Do not use the deprecated Toolkit getFontList() method.