Page 222 - Introduction to Programming with Java: A Problem Solving Approach
P. 222

                188 Chapter 5 Using Pre-Built Methods
Notice that the getImage method call has the word this as a prefix, and the word this also ap- pears in the last argument in the two calls to the drawImage method. The next chapter will explain that the special Java term this refers to whatever object happened to call the currently executing method. In our GraphicsDemo program, this refers to the object that calls the paint method, and that object is an instance of the GraphicsDemo class defined by the code in Figure 5.17. But where is the code that creates a GraphicsDemo object, where is the code that retrieves a reference to the associated Graphics object, and where is the code that calls the paint method? It’s in a separate file. . . .
Applet Execution
Did you notice that there is no main method in Figure 5.17? A Java applet is different from a Java applica- tion. Because a Java applet does not have a main method, it cannot be executed in the normal manner. Typi- cally, it’s embedded in another program, such that its code executes when that other program calls it. The primary purpose of a Java applet is to liven up a Web page. So we typically call Java applets from HTML (HyperText Markup Language) programs that define Web pages. Figure 5.18 contains a minimal HTML program that calls the GraphicsDemo applet defined in Figure 5.17.
Notice that the part of this HTML code that’s specific to our particular applet is all in the fifth line. This identifies the compiled version of the applet, and it specifies the pixel width and pixel height of the window that will hold whatever the applet will display. You can write this HTML code with any primitive text edi- tor, like Microsoft notepad or UNIX vi. Then save it in the same directory as the code that has the compiled version of the applet it drives. For example, in the directory that contains the GraphicsDemo.class file. When you save it, give it a name which has the html extension, like graphicsDemo.html.
You have three alternate ways to run the HTML file (and its associated Java applet):
Apago PDF Enhancer
1. Open a browser like Microsoft’s Internet Explorer, navigate to the directory that contains the HTML file, and double click on the HTML filename.
2. Open a Command Prompt Window, navigate to the directory that contains the HTML file, and enter: appletviewer graphicsDemo.html
3. Select “Run a Java Applet” in your local IDE (Integrated Development Environment), and select the desired HTML filename.
 <!DOCTYPE html>
<html>
<head></head>
<body>
name of file containing compiled Java applet code
   <applet code="GraphicsDemo.class" width="640" height="640">
</applet>
</body>
</html>
size of display window
  Figure 5.18 Code for an HTML file that runs the GraphicsDemo code in Figure 5.17














































































   220   221   222   223   224