1 /* 2 * File: FontMetricsTest2.java 3 * 4 * Given a string, center the string both vertically and 5 * horizontally in the applet window. 6 * 7 * Copyright: Northeast Parallel Architectures Center 8 * 9 */ 10 11 import java.applet.Applet; 12 import java.awt.Graphics; 13 import java.awt.Font; 14 import java.awt.FontMetrics; 15 16 public class FontMetricsTest2 extends Applet { 17 18 private String s; 19 20 public void init() { 21 22 // Get the "stringToDraw" parameter from the HTML document: 23 s = getParameter( "stringToDraw" ); 24 if ( s == null ) s = "Merry Christmas!"; 25 26 // Instantiate a font object: 27 Font f = new Font( "Serif", Font.ITALIC, 24 ); 28 29 // Set the font: 30 this.getGraphics().setFont( f ); 31 32 // Set the background color of the applet: 33 this.setBackground( java.awt.Color.cyan ); 34 35 } 36 37 public void paint( Graphics g ) { 38 39 // Get the FontMetrics object associated with this applet: 40 FontMetrics fm = g.getFontMetrics(); 41 42 // Determine the width of the applet: 43 int appletWidth = this.getSize().width; 44 45 // Determine the width of the string: 46 int stringWidth = fm.stringWidth( s ); 47 48 // Calculate the x-coordinate of the string: 49 int x = (appletWidth - stringWidth)/2; 50 51 // Determine the height of the applet: 52 int appletHeight = this.getSize().height; 53 54 // Calculate the height of *any* string: 55 int ascent = fm.getAscent(); 56 int descent = fm.getDescent(); 57 int stringHeight = ascent + descent; 58 59 // Calculate the y-coordinate of the string: 60 int y = (appletHeight - stringHeight)/2 + ascent; 61 62 // Draw the string at point (x,y): 63 g.drawString( s, x, y ); 64 65 } 66 67 }