Chapter 3 Introduction to Java Applets 121 1 (Web site builder)
Friday, August 24th, 2007Chapter 3 Introduction to Java Applets 121 1 // Fig. 3.8: WelcomeApplet2.java 2 // Displaying multiple strings in an applet. 3 4 // Java core packages 5 import java.awt.Graphics; // import class Graphics 6 7 // Java extension packages 8 import javax.swing.JApplet; // import class JApplet 9 10 public class WelcomeApplet2 extends JApplet { 11 12 // draw text on applet s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super.paint( g ); 17 18 // draw two Strings at different locations 19 g.drawString( “Welcome to”, 25, 25 ); 20 g.drawString( “Java Programming!”, 25, 40 ); 21 22 } // end method paint 23 24 } // end class WelcomeApplet2 Pixel coordinate (25, 40), where Java Programming! is displayed Pixel coordinate (25, 25), where Welcome to is displayed Fig. 3.8Applet that displays multiple strings. Fig. 3. 1 2 4 Fig. 3.9 WelcomeApplet2.htmlloads class WelcomeApplet2of Fig. 3.8 into the appletviewer. Note that each call to method drawString can draw at any pixel location on the applet. The reason the two output lines appear left aligned as shown in Fig. 3.8 is that both use the same x coordinate (25). Also, each drawString method call uses different y coordinates (25 on line 19 and 40 on line 20), so the strings appear at different vertical locations on the applet. If we reverse lines 19 and 20 in the program, the output window will still appear as shown because the pixel coordinates specified in each drawString statement are independent of the coordinates specified in all other drawString statements (and all other drawing operations). When drawing graphics, lines of text are not separated by newline characters (as shown with methods System.out s method println and JOptionPane s method showMessageDialog in Chapter 2). In fact, if you try Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01