1  /*
  2   *  File:  FontMetricsTest.java
  3   *
  4   *  Given a string, center the string horizontally in the 
  5   *  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 FontMetricsTest extends Applet {
 17  
 18     private String s;
 19     
 20     public void init() {
 21        
 22        // The string to be drawn:
 23        s = "Today is your lucky day!";
 24        
 25        // Instantiate a font object:
 26        Font f = new Font( "Serif", Font.PLAIN, 18 );
 27        
 28        // Set the font:
 29        this.getGraphics().setFont( f );
 30        
 31        // Set the background color of the applet:
 32        this.setBackground( java.awt.Color.cyan );
 33        
 34     }
 35     
 36     public void paint( Graphics g ) {
 37        
 38        // Determine the width of the applet:
 39        int appletWidth = this.getSize().width;
 40        
 41        // Determine the width of the string:
 42        int stringWidth = g.getFontMetrics().stringWidth( s );
 43        
 44        // Calculate the x-coordinate of the string:
 45        int x = (appletWidth - stringWidth)/2;
 46        
 47        // Specify the y-coordinate of the string:
 48        int y = 50;
 49        
 50        // Draw the string at point (x,y):
 51        g.drawString( s, x, y );
 52        
 53     }
 54     
 55  }