614 Graphics and Java2D (Photoshop web design) Chapter 11 Portability Tip
614 Graphics and Java2D Chapter 11 Portability Tip 11.2 The number of fonts varies greatly across systems. The J2SDK guarantees that the fonts Serif, Monospaced, SansSerif, Dialogand DialogInputwill be available. Common Programming Error 11.2 Specifying a font that is not available on a system is a logic error. Java will substitute that system s default font. The program of Fig. 11.9 displays text in four different fonts, with each font in a different size. The program uses the Fontconstructor to initialize Fontobjects on lines 30, 35, 40 and 47 (each in a call to Graphicsmethod setFontto change the drawing font). Each call to the Font constructor passes a font name (Serif, Monospaced or Sans- Serif) as a String, a font style (Font.PLAIN, Font.ITALICor Font.BOLD) and a font size. Once Graphics method setFont is invoked, all text displayed following the call will appear in the new font until the font is changed. Note that line 35 changes the drawing color to red, so the next string displayed appears in red. 1 // Fig. 11.9: Fonts.java 2 // Using fonts 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class Fonts extends JFrame { 12 13 // set window’s title bar and dimensions 14 public Fonts() 15 { 16 super( “Using fonts” ); 17 18 setSize( 420, 125 ); 19 setVisible( true ); 20 } 21 22 // display Strings in different fonts and colors 23 public void paint( Graphics g ) 24 { 25 // call superclass’s paint method 26 super.paint( g ); 27 28 // set current font to Serif (Times), bold, 12pt 29 // and draw a string 30 g.setFont( new Font( “Serif”, Font.BOLD, 12 ) ); 31 g.drawString( “Serif 12 point bold.”, 20, 50 ); 32 Fig. 11.9 Using Graphicsmethod setFontto change Fonts (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01