// From text by Cay Horstmann: Computing Concepts and // Java Essentials, 2003 (3rd edition). import java.applet.Applet; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; /** This applet draws a string that is centered in the applet window. */ public class FontApplet extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; // select the font into the graphics context final int HUGE_SIZE = 48; Font hugeFont = new Font("Serif", Font.BOLD, HUGE_SIZE); g2.setFont(hugeFont); String message = "Applet"; // measure the string FontRenderContext context = g2.getFontRenderContext(); Rectangle2D bounds = hugeFont.getStringBounds(message, context); double yMessageAscent = -bounds.getY(); double yMessageDescent = bounds.getHeight() + bounds.getY(); double yMessageHeight = bounds.getHeight(); double xMessageWidth = bounds.getWidth(); // center the message in the window double xLeft = (getWidth() - xMessageWidth) / 2; double yTop = (getHeight() - yMessageHeight) / 2; double yBase = yTop + yMessageAscent; g2.drawString(message, (float)xLeft, (float)yBase); // draw bounding rectangle g2.draw(new Rectangle2D.Double(xLeft, yTop, xMessageWidth, yMessageHeight)); // draw base line g2.draw(new Line2D.Double(xLeft, yBase, xLeft + xMessageWidth, yBase)); } }