.NODE

Simple Java Applet: Drawing a String

Simple Java Applet Drawing a String

Every Java applet is a graphical user interface on which you can place GUI components using the techniques introduced in Chapter 11 or draw using the techniques demonstrated in Chapter 12. In this chapter, we will demonstrate drawing on an applet. Examples in Chapters 21, 23 and 24 demonstrate building an applet's graphical user interface.

Now let's build an applet of our own. We begin with a simple applet (Fig. 20.6) that draws "Welcome to Java Programming!" on the applet. Figure 20.7 shows this applet executing in two applet containersthe appletviewer and the Microsoft Internet Explorer Web browser. At the end of this section, you will learn how to execute the applet in a Web browser.

Figure 20.6. Applet that draws a string.

(This item is displayed on page 965 in the print version)

 1 // Fig. 20.6: WelcomeApplet.java
 2 // A first applet in Java.
 3 import java.awt.Graphics; // program uses class Graphics
 4 import javax.swing.JApplet; // program uses class JApplet 
 5
 6 public class WelcomeApplet extends JApplet
 7 {
 8 // draw text on applet's background 
 9 public void paint( Graphics g ) 
10 { 
11  // call superclass version of method paint 
12  super.paint( g ); 
13 
14  // draw a String at x-coordinate 25 and y-coordinate 25
15  g.drawString( "Welcome to Java Programming!", 25, 25 );
16 } // end method paint 
17 } // end class WelcomeApplet

Figure 20.7. Sample outputs of the WelcomeApplet in Fig. 20.6.

(This item is displayed on page 965 in the print version)

 

Creating the Applet Class

Line 3 imports class Graphics to enable the applet to draw graphics, such as lines, rectangles, ovals and strings of characters. Class JApplet (imported at line 4) from package javax.swing is used to create applets. As with applications, every Java applet contains at least one public class declaration. An applet container can create only objects of classes that are public and extend JApplet (or the Applet class from early versions of Java). For this reason, class WelcomeApplet (lines 617) extends JApplet.

An applet container expects every Java applet to have methods named init, start, paint, stop and destroy, each of which is declared in class JApplet. Each new applet class you create inherits default implementations of these methods from class JApplet. These methods can be overridden (redefined) to perform tasks that are specific to your applet. Section 20.4 discusses each of these methods in more detail.

When an applet container loads class WelcomeApplet, the container creates an object of type WelcomeApplet, then calls three of the applet's methods. In sequence, these three methods are init, start and paint. If you do not declare these methods in your applet, the applet container calls the inherited versions. The superclass methods init and start have empty bodies, so they do not perform any tasks. The superclass method paint does not draw anything on the applet.

You might wonder why it is necessary to inherit methods init, start and paint if their default implementations do not perform tasks. Some applets do not use all three of these methods. However, the applet container does not know that. Thus, it expects every applet to have these methods, so that it can provide a consistent start-up sequence for each applet. This is similar to applications' always starting execution with main. Inheriting the "default" versions of these methods guarantees that the applet container can execute each applet uniformly. Also, inheriting default implementations of these methods allows the programmer to concentrate on defining only the methods required for a particular applet.

Overriding Method paint for Drawing

To enable our applet to draw, class WelcomeApplet overrides method paint (lines 916) by placing statements in the body of paint that draw a message on the screen. Method paint receives a parameter of type Graphics (called g by convention), which is used to draw graphics on the applet. You do not call method paint explicitly in an applet. Rather, the applet container calls paint to tell the applet when to draw, and the applet container is responsible for passing a Graphics object as an argument.

Line 12 calls the superclass version of method paint that was inherited from JApplet. This statement should be the first statement in every applet's paint method. Omitting it can cause subtle drawing errors in applets that combine drawing and GUI components.

Line 15 uses Graphics method drawString to draw Welcome to Java Programming! on the applet. The method receives as arguments the String to draw and the x-y coordinates at which the bottom-left corner of the String should appear in the drawing area. When line 15 executes, it draws the String on the applet at the coordinates 25 and 25.

20.3.1. Executing an Applet in the appletviewer

As with application classes, you must compile an applet class before it can execute. After creating class WelcomeApplet and saving it in the file WelcomeApplet.java, open a command window, change to the directory in which you saved the applet class declaration and compile class WelcomeApplet.

Recall that applets are embedded in Web pages for execution in an applet container (appletviewer or a browser). Before you can execute the applet, you must create an HTML (HyperText Markup Language) document that specifies which applet to execute in the applet container. Typically, an HTML document ends with an ".html" or ".htm" file-name extension. Figure 20.8 shows a simple HTML documentWelcomeApplet.htmlthat loads the applet defined in Fig. 20.6 into an applet container. [Note: If you are interested in learning more about HTML, the CD that accompanies this book contains three chapters from our book Internet and World Wide Web How to Program, Third Edition that introduce the current version of HTML (known as XHTML) and the Web page formatting capability known as Cascading Style Sheets (CSS).]

Figure 20.8. WelcomeApplet.html loads WelcomeApplet (Fig. 20.6) into an applet container.

 1 
2 "WelcomeApplet.class" width = "300" height = "45"> 3 4

Most HTML elements are delimited by pairs of tags. For example, lines 1 and 4 of Fig. 20.8 indicate the beginning and the end, respectively, of the HTML document. All HTML tags begin with a left angle bracket, <, and end with a right angle bracket, >. Lines 23 specify an applet element that tells the applet container to load a specific applet and defines the size of the applet's display area (its width and height in pixels) in the applet container. Normally, the applet and its corresponding HTML document are stored in the same directory on disk. Typically, a browser loads an HTML document from a computer (other than your own) connected to the Internet. However, HTML documents also can reside on your computer (as you saw in Section 20.2). When an applet container encounters an HTML document that contains an applet, the applet container automatically loads the applet's .class file (or files) from the same directory on the computer in which the HTML document resides.

The applet element has several attributes. The first attribute in line 2, code = "WelcomeApplet.class", indicates that the file WelcomeApplet.class contains the compiled applet class. The second and third attributes in line 2 indicate the width (300) and the height (45) of the applet in pixels. The tag (line 3) terminates the applet element that began at line 2. The tag (line 4) terminates the HTML document.

Look-and-Feel Observation 20.1

To ensure that it can be viewed properly on most computer screens, an applet should generally be less than 1024 pixels wide and 768 pixels talldimensions supported by most computer screens.

Common Programming Error 20.1

Forgetting the ending tag prevents the applet from executing in some applet containers. The appletviewer terminates without indicating an error. Some Web browsers simply ignore the incomplete applet element.

Error-Prevention Tip 20.1

If you receive a MissingResourceException error message when loading an applet into the appletviewer or a browser, check the tag in the HTML document carefully for syntax errors, such as commas (,) between the attributes.

The appletviewer understands only the and HTML tags and ignores all other tags in the document. The appletviewer is an ideal place to test an applet and ensure that it executes properly. Once the applet's execution is verified, you can add its HTML tags to a Web page that others can view in their Web browsers.

To execute WelcomeApplet in the appletviewer, open a command window, change to the directory containing your applet and HTML document, then type


 appletviewer WelcomeApplet.html

Error-Prevention Tip 20.2

Test your applets in the appletviewer applet container before executing them in a Web browser. Browsers often save a copy of an applet in memory until all the browser's windows are closed. If you change an applet, recompile it, then reload it in your browser, the browser may still execute the original version of the applet. Close all your browser windows to remove the old applet from memory. Open a new browser window and load the applet to see your changes.

Error-Prevention Tip 20.3

Test your applets in every Web browser in which they will execute to ensure that they operate correctly.

 

20.3.2. Executing an Applet in a Web Browser

The sample program executions in Fig. 20.6 demonstrate WelcomeApplet executing in the appletviewer and in Microsoft Internet Explorer Web browser. To execute an applet in Internet Explorer, perform the following steps:

1.

Select Open... from the File menu.
 

2.

In the dialog box that appears, click the Browse... button.
 

3.

In the dialog box that appears, locate the directory containing the HTML document for the applet you wish to execute.
 

4.

Select the HTML document.
 

5.

Click the Open button.
 

6.

Click the OK button.
 

[Note: The steps for executing applets in other Web browsers are similar.]

If your applet executes in the appletviewer, but does not execute in your Web browser, Java may not be installed and configured for your browser. In this case, visit the Web site java.com and click the Get It Now button to install Java for your browser. In Internet Explorer, if this does not fix the problem, you might need to manually configure Internet Explorer to use J2SE 5.0. To do so, click the Tools menu and select Internet Options..., then click the Advanced tab in the window that appears. Locate the option "Use JRE v1.5.0 for(requires restart)" and ensure that it is checked, then click OK. Close all your browser windows before attempting to execute another applet in the browser.

 

 


[Page 968 (continued)]

20 4 Applet Life Cycle Methods

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover





Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net