1 /* 2 * File: FontModel.java 3 * 4 * Given two strings and a point, draw the first string at the 5 * point and the second string underneath the first. For each 6 * string, draw the baseline under the string and the bounding 7 * box around the string. 8 * 9 * Copyright: Northeast Parallel Architectures Center 10 * 11 */ 12 13 import java.applet.Applet; 14 import java.awt.Graphics; 15 import java.awt.Font; 16 import java.awt.FontMetrics; 17 18 public class FontModel extends Applet { 19 20 private String s1, s2; 21 public String fontName = "Serif"; 22 public String fontSizeString = "24"; 23 24 public void init() { 25 26 // The strings to be drawn: 27 s1 = "How razorback-jumping frogs"; 28 s2 = "can level six piqued gymnasts!"; 29 30 // Set the background color of the applet: 31 this.setBackground( java.awt.Color.cyan ); 32 33 } 34 35 public void paint( Graphics g ) { 36 37 // Save the default font: 38 Font defaultFont = g.getFont(); 39 40 // Instantiate a font object and set the font: 41 int fontSize = Integer.parseInt( fontSizeString ); 42 Font displayFont = new Font( fontName, Font.BOLD, fontSize ); 43 g.setFont( displayFont ); 44 45 // Calculate the height of *any* string in this font: 46 int ascent = g.getFontMetrics().getAscent(); 47 int descent = g.getFontMetrics().getDescent(); 48 int stringHeight = ascent + descent; 49 50 // The location of the first string: 51 int x = 25, y = 75; 52 53 // Draw the first string at point (x,y): 54 g.drawString( s1, x, y ); 55 56 // Determine the width of the first string: 57 int stringWidth = g.getFontMetrics().stringWidth( s1 ); 58 59 // Draw the baseline under the first string: 60 g.drawLine( x, y, x + stringWidth, y); 61 62 // Draw a dot centered at (x,y): 63 int r = 3; // radius of the dot 64 g.fillOval( x - r, y - r, 2*r, 2*r ); 65 66 // Draw the bounding box around the first string: 67 g.drawRect( x, y - ascent, stringWidth, stringHeight ); 68 69 // Draw labels next to the bounding box: 70 g.setFont( defaultFont ); 71 int dy = g.getFontMetrics().getAscent(); 72 g.drawString( "ascent", x + stringWidth + 5, y - ascent + dy ); 73 g.drawString( "descent", x + stringWidth + 5, y + descent ); 74 g.setFont( displayFont ); 75 76 // Determine the font height: 77 int fontHeight = g.getFontMetrics().getHeight(); 78 79 // Calculate the y-coordinate of the second string: 80 y += fontHeight; 81 82 // Draw the second string at point (x,y): 83 g.drawString( s2, x, y ); 84 85 // Determine the width of the second string: 86 stringWidth = g.getFontMetrics().stringWidth( s2 ); 87 88 // Draw the baseline under the second string: 89 g.drawLine( x, y, x + stringWidth, y); 90 91 // Draw a dot centered at (x,y): 92 g.fillOval( x - r, y - r, 2*r, 2*r ); 93 94 // Draw the bounding box around the first string: 95 g.drawRect( x, y - ascent, stringWidth, stringHeight ); 96 97 // Restore the default font: 98 g.setFont( defaultFont ); 99 } 100 101 }