1 /* 2 * File: FontMetricsTest3.java 3 * 4 * Given two strings, center the strings 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 FontMetricsTest3 extends Applet { 17 18 private String s0, s1; // two strings to be drawn 19 20 public void init() { 21 22 // Get the "string0" parameter from the HTML document: 23 s0 = getParameter( "string0" ); 24 if ( s0 == null ) s0 = "string0 goes here"; 25 26 // Get the "string1" parameter from the HTML document: 27 s1 = getParameter( "string1" ); 28 if ( s1 == null ) s1 = "string1 goes here"; 29 30 // Get the "fontName" parameter from the HTML document: 31 String name = getParameter( "fontName" ); 32 if ( name == null ) name = "Serif"; 33 34 // Instantiate a font object: 35 Font f = new Font( name, Font.BOLD + Font.ITALIC, 24 ); 36 37 // Set the font: 38 this.getGraphics().setFont( f ); 39 40 // Set the background color of the applet: 41 this.setBackground( java.awt.Color.cyan ); 42 43 } 44 45 public void paint( Graphics g ) { 46 47 // Get the FontMetrics object associated with this applet: 48 FontMetrics fm = g.getFontMetrics(); 49 50 // Determine the width of the applet: 51 int appletWidth = this.getSize().width; 52 53 // Determine the width of the first string: 54 int stringWidth = fm.stringWidth( s0 ); 55 56 // Calculate the x-coordinate of the first string: 57 int x = (appletWidth - stringWidth)/2; 58 59 // Determine the height of the applet: 60 int appletHeight = this.getSize().height; 61 62 // Calculate the height of *any* string: 63 int ascent = fm.getAscent(); 64 int descent = fm.getDescent(); 65 int stringHeight = ascent + descent; 66 67 // Calculate the height of both strings: 68 int leading = fm.getLeading(); 69 int height = 2 * stringHeight + leading; 70 71 // Calculate the y-coordinate of the first string: 72 int y = (appletHeight - height)/2 + ascent; 73 74 // Draw the first string at point (x,y): 75 g.drawString( s0, x, y ); 76 77 // Calculate the width of the second string: 78 stringWidth = fm.stringWidth( s1 ); 79 80 // Calculate the x-coordinate of the second string: 81 x = (appletWidth - stringWidth)/2; 82 83 // Calculate the font height: 84 int fontHeight = stringHeight + leading; 85 86 // Calculate the y-coordinate of the second string: 87 y += fontHeight; 88 89 // Draw the second string at point (x,y): 90 g.drawString( s1, x, y ); 91 92 } 93 94 }