When you write strings, the strings are placed on a
baseline. Portions of all characters appear
above the baseline. Characters such as g
and p
have
descenders that appear below the baseline.
The distance by which a font extends above the baseline is that font's height, whereas the distance by which the font's characters extends below the baseline is the font's descent.
The getFontMetrics
method returns an instance of the
FontMetrics
class. That instance provides height and descent
information, via the getHeight
and getDescent
methods, for the font currently associated with a graphics context. The
FontMetrics
instance also provides string-width information, via the
stringWidth
method, for a string argument. The
stringWidth
method returns the width that the string would occupy if
the string were displayed in the font associated with the
FontMetrics
instance.
You can use information about height and widthusing getHeight
and
stringWidth
to
position a string that you
draw. In the following example, stringWidth
makes it possible to
center the string on a baseline located at the middle of the window. The
size of the font used varies with the width of the window.
import java.awt.*; import javax.swing.*; public class Meter extends JComponent implements MeterInterface { String title = "Title to Be Supplied"; int minValue, maxValue, value; public Meter (int x, int y) { minValue = x; maxValue = y; value = (y + x) / 2; } public void setValue(int v) {value = v; repaint();} public void setTitle(String t) {title = t; repaint();} // Define getValuesAtCoordinates as in Segment 745 public void paint(Graphics g) { // Determine window size: Dimension d = getSize(); // Prepare font int fontSize = d.width / 30; g.setFont(new Font("Helvetica", Font.BOLD, fontSize)); // Write title: FontMetrics f = g.getFontMetrics(); int stringWidth = f.stringWidth(title); int xOffset = (d.width - stringWidth) / 2; int yOffset = d.height / 2; g.drawString(title, xOffset, yOffset); } public Dimension getMinimumSize() {return new Dimension(150, 100);} public Dimension getPreferredSize() {return new Dimension(150, 100);} }