by Rogers Cadenhead
Although Java is a general-purpose programming language suitable for a large variety of tasks, the task most people use it for is applet programming. An applet is a Java program that executes on a World Wide Web page.
When the prerelease versions of the Java Developers Kit were made available in 1995, the demonstration programs that drew international attention to the language were applets. Your first experience with Java might have been one of these demos-spinning heads, the animated Duke character doing cartwheels, a dancing headline, and so on. Those applets are still available on the JavaSoft site at the following URL:
http://java.sun.com/java.sun.com/applets/applets.html
Today, applets are being used to accomplish far more than demonstrative goals. There are working examples of applets on Web sites throughout the Internet-a check of the AltaVista search engine finds more than 4,200 Web pages that have applets embedded on them.
The current uses of applets include the following:
Figure 17.1 shows a noteworthy example of an applet: the Instant
Ballpark program from
Instant Sports.
Figure 17.1: The Instant Ballpark applet (courtesy of Instant Sports).
Instant Ballpark takes real-time data from live baseball games and updates its display to reflect what's happening in the game. Players run the bases, the ball goes to the place it was hit, and sound effects are used for strike calls, crowd noise, and other elements. The program, which was unique enough to qualify for a U.S. patent, is reminiscent of the old-time baseball tradition of presenting the play-by-play for road games by moving metal figures on the side of a building. In addition to the live coverage, Instant Ballpark can be used to review the play-by-play action of past games.
The applet shows one of the advantages of a Web program over a Web page. With HTML and some kind of gateway programming language such as Perl, a Web page can offer textual updates to a game in progress. However, Instant Ballpark offers a visual presentation of a live game in addition to text, and the applet can respond immediately to user input. Java can be used to provide information to Web users in a more compelling way, which is often the reason site providers are offering applets.
To try this applet, visit the following Web site:
http://www.instantsports.com/ballpark.html
As you know, applets are displayed as a part of a Web page. A special HTML tag, <APPLET>, is used to attach a Java applet to an HTML page. Running an applet requires the use of a Web browser or other software that serves the function of a browser, such as the applet viewer program that ships with the Java Developers Kit from JavaSoft.
The browser acts as the operating system for applets-you cannot run an applet as a standalone program in the same way you can run an executable file.
At the time of this writing, there are three widely available Web browsers that can run Java applets:
These programs load applets from a Web page and run them remotely on the Web user's computer. This arrangement raises security issues that must be handled by the Java language itself and by Java-enabled browsers. These browsers are covered in detail in Chapter 3, "Browsing Java."
Java applets are programs that run on a Web user's machine. Anything that can execute code is a potential security risk because of the damaging things that can occur. Viruses can damage a computer's file system and reproduce onto other disks, Trojan horses can masquerade as helpful programs while doing harmful things, and programs can be written to retrieve private information surreptitiously. Even Microsoft Word has been a security risk because of Word Basic-an executable programming language that can be used in conjunction with Word documents.
Security is one of the primary concerns of Java's developers, and they have implemented safeguards at several levels. Some of these safeguards affect the language as a whole: The removal of pointers, the verification of bytecodes, and other language issues have been discussed elsewhere in this book.
Some of Java's functionality is not possible when programming applets because of security concerns. The following safeguards are in place:
As you can see, Java applets are more limited in functionality than standalone Java applications. The loss is a tradeoff for the security that must be in place for the language to run remotely on users' computers.
The security restrictions discussed here are current as of the
1.0.2 release of the Java Developers Kit. JDK version 1.1 is in
development as of this writing, but it is expected to add more
security rather than lessening any of the existing safeguards.
Refer to Chapter 35, "Java Security,"
for more information.
A word about applications |
This chapter focuses on applets, but it's important to make clear the distinction between the two types of Java programs. Applets are programs offered on Web pages that require the use of a Web browser to execute. Applications are everything else: general-purpose programs run by executing the Java interpreter with the name of the Java program as an argument. For example, to run the Java program ReadNews.class, enter the following at a command-line prompt: java ReadNews Applications do not have any of the restrictions that are in place for applets. |
Now that you understand what applets are, it's time to get out the tools and build one. Before starting the project, however, the following sections introduce some basic elements of applet programming.
Each applet starts out with a class definition such as the following:
public class LearnPigLatin extends java.applet.Applet { // to do }
In this example, LearnPigLatin is the name of the applet's class. An applet must be declared as a public class. Applets are subclasses of java.applet.Applet, which is a subclass of the java.awt.Panel class. Figure 17.2 shows the full class hierarchy tree of the Applet class.
Figure 17.2: The hierarchy of Java.applet.Applet.
The superclasses of Applet give all applets a framework on which you can build user interface elements and mouse events. These superclasses also provide a structure for the applet that must be used when the program is developed.
The structure of an applet takes the form of five events that can take place as an applet is running. When the events occur, a method is automatically called. The methods also can be called directly within the applet. The methods are the following:
The last of the methods, paint(), must take a parameter-an instance of the Graphics class-as in the following method definition:
public void paint(Graphics g) { g.drawString("One moment, please", 5, 50); }
A Graphics object is used to indicate where something should be drawn. The Graphics object used as the parameter to paint() is created automatically, and it represents the applet window. The g.drawString() line uses this Graphics object to indicate where a string should be drawn. Every time the repaint() method is called and the applet window must be updated, the string One moment, please is drawn at the x, y position (in this example, 5, 50).
The Graphics object does not have to be declared. However, the .Graphics class must be imported at the beginning of an applet's source code. Here's what that import statement should look like:
import java.awt.Graphics;
Each of these applet methods-init(), destroy(), start(), stop(), and paint()-is inherited by an applet. You do not have to write your own methods for any of these.
However, each of the applet methods is empty by default. If something is supposed to happen in an applet, some or all of these methods must be overridden.
For a Java applet to be run when a Web page is loaded, information about that applet must be put on the page. This requires the use of two special HTML tags: <APPLET> and <PARAM>. This HTML code is included on a Web page along with all other HTML code. In this respect, putting a Java applet on your home page is no different than putting a picture there.
Java applets can be viewed by Web browsers and any other software that is equipped to load applets, such as the applet viewer utility that comes with the Java Developers Kit.
Following is an example of an applet tag:
<APPLET CODE="NowShowing.class" CODEBASE="progdir" WIDTH=376 HEIGHT=104> <PARAM NAME="speed" value="100"> <PARAM NAME="blink" value="5"> <PARAM NAME="text" value="FREE THE BOUND PERIODICALS!"> <PARAM NAME="fontsize" value="21"> <PARAM NAME="pattern" value="random"> <H5>This applet requires the use of a Java-enabled browser!</H5> </APPLET>
When included on a Web page, this HTML code causes the following to take place on a Java-enabled browser:
The HTML code causes the following to take place on a browser that is not equipped to run Java programs:
Browsers that do not handle Java programs disregard everything within the <APPLET>, </APPLET>, and <PARAM> tags. As shown in the preceding HTML code of an applet tag, an alternative can be provided for browsers that do not handle Java.
The CODE attribute must be used in conjunction with the <APPLET> tag because it specifies the name of the applet's class file. This is the file that will be run after it has been loaded onto the Web user's computer.
If the CODEBASE attribute is used, it indicates the path from the Web page's directory to the directory containing the applet's class file. For example, CODEBASE="usr" indicates that the applet is in a directory called usr that is a subdirectory of the Web page's directory.
If the applet makes use of class files that are not part of the standard Java API, these class files must be located in the same directory as the applet's class file.
The HEIGHT and WEIGHT attributes should be familiar to anyone who has used them to place an image on a Web page-they work the same with <APPLET> as they do with <IMG>. The ALIGN attribute used with images also can be used with <APPLET>. The ALIGN attribute determines how the applet is positioned in relation to the other parts of the Web page and can have the values TOP, MIDDLE, or BOTTOM.
Parameters can be sent to an applet by using the <PARAM> tag and its two attributes: NAME and VALUE. Here's a line from the preceding example:
<PARAM NAME="blink" VALUE="100">
The value of the NAME attribute
assigns a name to an applet parameter, and VALUE
gives the parameter a value. The preceding statement sends a parameter
named blink with a value
of 100.
Note |
The name of a parameter is not case sensitive, so the capitalization of the value assigned to NAME does not matter. |
Parameters are sent to an applet when it is loaded; you can send as many parameters as you want. All parameters are sent to applets as strings and must be converted to other data types if they are needed as integers or other types.
For a parameter to be used by a Java applet, the applet must retrieve the parameter. This requires the getParameter() method, which is available to all applets because it is part of the Applet class.
For example, use the following line in a Java applet to store the blink parameter in a variable called blinkValue:
String blinkValue = getParameter("blink");
If you want to retrieve the value and convert it to an integer, use the following code:
int blinkValue = -1; try { blinkValue = Integer.parseInt(getParameter("blink")); } catch (NumberFormatException e) { }
This example uses the parseInt() method of the java.lang.Integer class to convert a String into an int. The try and catch block is used to trap errors if the String cannot be converted into a number.
When you have created an applet and added it to HTML pages, you easily can make it available on the World Wide Web. Put all .class files required by the applet on your Web site, making sure to put the files in the same directory as the CODEBASE attribute if it has been used. If not, put the .class files in the same directory as the Web page that includes the applet.
That's all it takes. Unlike CGI programming (which requires special access to the computer providing the Web pages), Java applets can be added by anyone who can put pages on a Web site.
In the next chapter, you will delve into specific details of applet programming, including user interface design and event handling. For now, it is worthwhile to take a look at a working example of an applet to get a clearer picture of how applets are designed.
The ColorCycle applet is a simple applet with one button labeled Next Color. When the button is clicked with the mouse, the background color of the applet changes.
The program demonstrates basic applet structure and a simple bit of event handling-how to respond to a mouse click on a button.
Listing 17.1 shows the full source code of ColorCycle.java. It can be found on the book's CD-ROM in the directory \WIN95NT4\SOURCE\CHAP17 (Windows 95 and Windows NT 4 users) or in the directory \SOURCE\CHAP17 (Macintosh users), along with the rest of the Java and HTML source code in this chapter. Windows NT 3.51 users must install the source code on their hard drives or select these files from the zipped source code located on the CD-ROM.
Listing 17.1. The source code of ColorCycle.java.
1: import java.awt.*; 2: 3: public class ColorCycle extends java.applet.Applet { 4: float hue = (float).5;6L5: float saturation = (float)1; 6: float brightness = (float)0;6L7: Button b; 8: 9: public void init() { 10: b = new Button("Next Color"); 11: add(b); 12: } 13: 14: public void start() { 15: setBackground(Color.black); 16: repaint(); 17: } 18: 19: public boolean action(Event evt, Object o) { 20: if (brightness < 1) 21: brightness += .25; 22: else 23: brightness = 0; 24: Color c = new Color(Color.HSBtoRGB(hue, saturation, brightness)); 25: setBackground; 26: repaint(); 27: return true; 28: } 29: }
Don't worry if some aspects of this program are unfamiliar to you at this point. Several aspects of this applet are discussed fully in the next chapter, including the creation of user interface components such as buttons and the action() method.
The following things are taking place in the applet:
Once the applet has been written and compiled using your development software, you can put it on a Web page using the HTML tags <APPLET>, </APPLET>, and <PARAM> described earlier in this chapter.
Listing 17.2 shows the full text of an HTML page that loads the ColorCycle.class applet (the source code can also be found on the CD-ROM that accompanies this book). The CODEBASE attribute is not used with the <APPLET> tag, so the ColorCycle.class file must be placed in the same directory as the Web page containing the applet.
Listing 17.2. The source code of ColorCycle.html.
1: <html> 2: <body> 3: <applet code=ColorCycle.java height=250 width=250> 4: </applet> 5: </body> 6: </html>
Although the applet loses something in the translation from color to black and white, Fig-ure 17.3 shows how the ColorCycle applet looks when loaded with Netscape Navigator 2.02 for Windows 95, one of the current Web browsers equipped to handle Java programs.
Figure 17.3: The ColorCycle applet.
This chapter provided a framework for the development of applets, but the actual details of creating a user interface and responding to interaction with the mouse and keyboard are coming up next.
As you will find when programming your own applets, the Java API has built-in functionality to handle a lot of the work for you. The user interface provides a lot of components such as buttons, text fields, and choice boxes, and subclassing makes it possible to extend these components without requiring a lot of new code.
Also, other tasks that can be arduous in some languages-such as animation and event handling-are relatively easy using Java.
One of Java's original design goals (back when the language was still known as Oak) was to be simple. When it comes to object-oriented programming, some folks might argue that it can never be simple. However, applet programming is a good area for novice Java programmers to begin because it can be easy to develop useful Web programs without a lot of coding.