import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Font; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; public class FontApplet extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; // select the font into the graphics context Font f = new Font("Serif", Font.BOLD, 48); g2.setFont(f); String message = "Applet"; // create a text layout to measure the string FontRenderContext context = g2.getFontRenderContext(); TextLayout layout = new TextLayout(message, f, context); // measure the message width and height float xMessageWidth = layout.getAdvance(); float yMessageHeight = layout.getAscent() + layout.getDescent(); // center the message in the window float xLeft = 0.5F * (getWidth() - xMessageWidth); float yTop = 0.5F * (getHeight() - yMessageHeight); float yBase = yTop + layout.getAscent(); g2.drawString(message, xLeft, yBase); } }