Okay you Web jockeys and Internet mavens, this chapter's for you. Application developers, don't despair. Remember, applets and applications have a lot in common. You'll learn a lot in this chapter too; don't take the day off.
Much of Java's current popularity has come about because of Java-capable World Wide Web browsers and their support for appletssmall programs that run inside a Web page and can be used to create dynamic, interactive Web applications. Applets, as
we noted at the beginning of this book, are written in the Java language (VJ++ being a development environment for Java), and can be viewed in any browser that supports Java, including Microsoft's Internet Explorer 3.0 and Netscape's Navigator 2.0x.
Learning how to create applets is probably the reason you bought this book, so we'll not take any more time.
From here on out, when we mention a browser or Web browser, we mean a Java-enabled browser. Otherwise, what is the point in developing applets?
For the past eight days, you focused on learning about the Java language itself, the VJ++ interface, and some of the VJ++ tools. Most of the little programs you have created thus far were Java applications, but now that you have the basics down, it's
time to move on to creating and using applets. We'll begin with a discussion of some of the classes in the standard Java class library.
Today, you'll start with the basics:
Although you have already explored the differences between Java applications and Java applets in the early part of this book, you can review them now.
In short, Java applications are standalone Java programs that can be run by using the VJ++ interpreter (JVIEW). Most everything you've done so far in the book have been Java applications, albeit simple ones.
Java applets, however, are run from inside a World Wide Web browser. A reference to an applet is embedded in a Web page using a special HTML tag. When a reader loads a Web page with an applet in it, the browser downloads that applet from the Web server
and executes it on the local system (the one the browser is running on).
Because Java applets run inside a Java browser, they have the advantage of using the structure already provided by the browser. The browser provides an existing window to run the applet, an event-handler and graphics context, and the surrounding user
interface. Even though Java applications can create this structure, they don't require it (you'll learn how to create Java applications that use applet-like graphics and User Interface (UI) features later on in this book).
The convenience of structure and UI capabilities that applets provide over applications, however, is offset by some restrictions placed upon applets. Given the fact that Java applets can be downloaded from any Web site and run on a user's personal
system, restrictions are necessary to prevent an applet from causing system damage or security breaches. Without these restrictions in place, Java applets could be written to contain viruses, or be used to compromise the security of the system that runs
them. The restrictions on what an applet can do include the following:
The last preceding item is true for a pure Java-enabled browser. Microsoft has extended the abilities of Java by providing support for COM objects, which, in effect, allow an applet to load COM objects from DLLs and EXEs that reside on the user's local machine. You will learn a bit about COM on Day 15.
In addition, Java itself includes various forms of security and consistency checking in the Java compiler and interpreter to prevent unorthodox use of the language (you'll learn more about this on Day 21). This combination of restrictions and security
features make it more difficult for a rogue Java applet to do damage to the client's system.
These restrictions help to prevent all the traditional ways of causing damage to a user's system. However, it's impossible to be absolutely sure that a clever programmer cannot work around these restrictions to violate privacy, use CPU resources, and generally be an annoyance. Sun has asked the Net to try and break Java's security and create an applet that can circumvent the restrictions. You'll learn about more issues in Java security on Day 21.
Keep this in the back of your mind as we go through the basic applet exercise today. The applets you create with VJ++ can include ActiveX objects. ActiveX objects are powerful, object-oriented extensions to the standard Java classes. For example,
ActiveX controls allow button bars, scrollbars, and Excel spreadsheets to be included on a Web page. However, if a Web page contains an applet that uses ActiveX, the user will need to download the extra Microsoft classes that support ActiveX. Although this
can be easily accomplished by your applets initialization class, the user might not want (or be able) to download the controls. The good news is that Microsoft Internet Explorer 3.0 automatically installs the extra classes; Netscape (and other browsers)
will probably do the same in the future. Also, in a press release dated July 26, 1996, Microsoft announced it would give up control of the ActiveX technology and help to move its control to an independent body. This should help to make ActiveX more
popular, resulting in a larger installed base. So, what you need to consider when designing your applets is whether or not to make your applets ActiveX (and Microsoft) specific, or more versatile, allowing ActiveX to coexist with the mundane standard Java
classes, non-Microsoft applications, and the variety of Web browsers out there. For more detailed information about ActiveX, pick up a copy of ActiveX Programming Unleashed, also published by Sams.net.
The VJ++ programs you've created up to this point have been Java applicationssimple programs using a single main() method that created objects, set data members, and ran methods. Today, and in the days following, you'll be creating applets
exclusively. To do this, you'll need a good grasp of how an applet works, the sorts of features an applet has, and where to start when you first create your own applets.
In general, an applet works when a user accesses a Web page that contains an applet. The browser then creates a local copy of the class file specified by an <APPLET> tag contained in the HTML file. As the browser is copying the class file, it's
also parsing the file. If the browser finds any import statements, and those classes aren't on the local machine, it copies those files too. Once the files are copied, the applet is loaded, and the browser creates an instance of the initial class (the one
specified by the <APPLET> tag). It's important to note here that from this point on, the browser and applet execute methods from the instance of the class it created and not from the original class. The instance of the class is then run by the
browser. The browser then automatically executes the init() and start() methods. The remainder of the methods in the class are executed by the applet.
You can already see how different (and dependent) the applet process is than the application process. Other than the browser, though, there is one major difference: when an application loads, JVIEW runs the main method within the initial class; it
doesn't make an instance of the initial class before running the main method like an applet does.
To create an applet, you create a subclass of the class Applet, from the java.Applet package. The Applet class provides behavior that enables your applet to work within the browser itself. It also enables it to take advantage of the capabilities of the
Abstract Windowing Toolkit (AWT) to draw to the screen when you include UI elements to handle mouse and keyword events. Although your applet can have as many helper classes as it needs, the main applet class is the one that triggers the execution of the
applet.
AWT is the Abstract Windowing Toolkit. It is a group of classes and containers you'll use when your programs require graphical user interface elements, such as buttons, lists, scrollbars, windows, and frames. The AWT will
be covered in detail on Day 12 and 13.
A helper is a class that doesn't contain the main method that started the current applet.
The initial main applet class always has a signature like the following, where myClass would be replaced with the name of your particular class:
public class myClass extends java.Applet.Applet { ... }
Note the public keyword. Java requires that your applet subclass be declared public. This is true only of the main applet class; any helper classes you create can be public or private; it's your choice. Public, private, and other forms of access
control are described on Day 17 when we discuss modifiers.
Hopefully you remember, when creating a basic Java application, your class has to have only one method, main(), with a specific signature. Then, when your application starts up, main() is executed, and then from main(), you can set up the behavior your
program needs.
Applets are similar in this respect, but they are a bit more complicated, because they rely on a browser to operate. During the life of an applet, many different activities correspond to various events, for example, initialization, painting, and mouse
actions. Each activity has a corresponding method, so when the event occurs, the applet depends upon the browser to call the methods specific to the event.
By default, however, all of the preceding methods do nothing, because the method corresponding to the event contains no default behavior. It's more or less an event place holder. To provide behavior for an event, you must override each method in your
applet's subclass, and give it the specific behavior you require. Java is structured this way because it's platform independent. Also, keep in mind you don't have to override all of the events, only the ones you need.
In other words, all applets are subclasses of the class applet. Class applet has methods that handle events, but the methods in applet don't actually do anything, they are simply holders for your behavior-specific methods. Therefore, if you want your
applet to do anything, you'll need to create member functions for each event trigger. By doing so, you will overload the methods in the superclass applet, superimposing your applet's methods behavior on top of each of its methods.
You'll learn about the various methods you might need to override as the week progresses, but, for a general overview, here are five of the more important applet execution method types: initialization, starting, stopping, destroying, and painting.
Initialization occurs when the applet is first loaded (or reloaded). Initialization might include creating needed objects, setting up an initial state, loading images or fonts, or setting parameters. To provide initialization behavior, override the
init() method:
public void init() { ... }
After an applet is initialized, it is started. Starting can also reoccur if the applet was previously stopped. For example, when a reader follows a link to a different page, the applet stopswhen the reader comes back to the page, the applet
restarts. Even though starting can occur several times during the life of an applet, initialization happens only once.
Functionality that you might include in the start() method could be starting an applet control thread, sending messages to helper objects, or simply telling the applet to begin running. You'll learn more about starting applets on Day 11.
To provide applet startup behavior, override the start() method:
public void start() { ... }
Stopping and starting go hand in hand. When the reader triggers an event signaling they are leaving the page containing applet currently running, a call is automatically placed by the browser to the stop() method.
When the browser leaves the page, any threads the applet had started, but not finished, will continue to run. You'll learn more about threads in Day 11. By overriding stop(), you can suspend execution of the threads and then restart them if the applet
is viewed again (started).
You stop the applet yourself by calling stop():
public void stop() { ... }
Destroying sounds more violent than it is. Destroying enables the applet to clean up after itself. It does this just before the applet is freed from memory or the browser exits. For example, destroying kills any running threads and releases any other
running objects. Generally, you won't need to override destroy() unless you need to release specific resources, such as threads the applet has created. To provide applet clean up behavior, override the destroy() method:
public void destroy() { ... }
How is destroy() different from finalize(), which was described on Day 8? First, destroy() applies only to applets and it applies to the applet as a whole; you destroy() when you exit the applet. finalize() is a more general purpose way a single object of any type can clean up after itself. In an applet, you can use bothfinalize() inside a class to clean up after itself, and destroy() to clean up before the applet exits.
Painting is how an applet draws something on the screen, whether it is text, a line, a colored background, or an image. Painting can occur hundreds of times during an applet's life. For example, painting can occur after the applet is initialized, when
the browser window is brought back to the foreground after being placed in the background by an overlapping window, when the browser window is moved to a different position, or repeatedly, when a Web page contains an animation. The paint() method looks
like this:
public void paint(Graphics g) { ... }
Unlike the other methods in this section, paint() uses arguments: an instance of the class Graphics and a context. The Graphics object is created and passed automatically to paint by the browser, so you don't have to worry about it. However, you will
have to make sure that the Graphics class (part of the java.awt package) gets imported into your applet code. This is usually and easily accomplished by using the import statement at the top of your applet file:
import java.awt.Graphics;
On Day 2, you created a simple applet called HelloAgainApplet (this was the one that displayed the big red Hello Again). That example was used to illustrate how to create a subclass. Today we're going to recreate that applet using the VJ++ Java Applet
Wizard. Along the way, we will go over each of the pieces of Java code that the Java Applet Wizard automatically creates for you.
Don't be mad at us for not showing you the Wizard earlier. By knowing the basics first, you'll appreciate and understand what the Wizard does.
As we're going through the following Wizard windows, we won't be explaining every bit of detail. If you want specific information, you can get it (and we recommend that you do) by clicking Help.
To begin, open Microsoft Developer Studio, select File | New | Project Workspace, and click OK. When the New Project Workspace window displays, select Java Applet Wizard, and for the Name, type NewHelloApplet (this is the name of the main class).
Notice VJ++ automatically creates a new Location (directory name) under the default project directory, based upon your applet's name. You should keep the location name that VJ++ creates. Also remember that Java expects (requires!) that the class name and
its filename be the samerespecting the same upper and lower case letters in the class and filename. VJ++ and the Wizard take care of this for you. Make sure, under Platforms, that Java Virtual Machine is selected, and then click Create. (See
Figure 9.1.)
Figure 9.1. A completed New Project Workspace window.
Notice that the Wizard can add the proper code to have your applet run as an applet (which requires a browser to run) or as both an applet and an application (a standalone program). Select As an applet only. Leave the name of your applet class
alone. The Wizard can also add explanatory comments and To Do comments. Both of these options are very helpful when you're working on your own and creating your own applets. Explanatory comments are disbursed throughout the applet, describing the function
of each method. To Do indicators are placed in code sections where the Wizard can't determine the specific code to create, and you'll need to add your own. For your purposes, we'll elect not to generate comments, so they don't clutter up the workspace and
prevent a clear view of the actual code. Select No, thank you, and then click Next. (See Figure 9.2.)
Figure 9.2. A completed Step 1 of 5 window.
The options in this window help you with testing your applet. The Wizard will create a skeleton HTML file containing a window in which to execute your applet. This is great for a couple of reasons. You might be a Java developer who doesn't know much
about HTML, possibly because your company has HTML authors for that. Even if you do know HTML, you won't need to spend the time to create an HTML file simply for testing purposes. The initial applet size is measured in pixels (based on the values you
supplied). Later, you can change the size by editing the values in the init() method of your source code, or it is also possible to create a dynamically sized window using the methods that determine screen size (getScreenSize()) and screen resolution
(getScreenResolution()).
For now, you'll keep the default selections, and then click Next. (See Figure 9.3.)
Figure 9.3. A completed Step 2 of 5 window.
These options handle how your applet behaves. Multithreaded, as discussed briefly earlier, allows your applet to spawn multiple processes that allow multiple things to appear to happen simultaneously. Displaying an animated image on a Web page is an
example of multithreading. The multithreaded option adds a significant amount of code to your applet, select No, thank you. Notice that when you elect not to have a multithreaded program, the options for animation and sample images become grey. These are
unselectable now, because you must have support for multithreading to display an animation. If you didn't, your applet would display only the animated image and not give up any processing cycles to handle an exit event, which would be bad! Your last choice
on this screen is to handle mouse events. More than likely, in your applets you'll choose to have these events handled. For your simple purposes, though, we'll choose not to support mouse eventsleave the options unselected, and then click Next. (See
Figure 9.4).
Figure 9.4. A completed Step 3 of 5 window.
The list box displayed in this window allows you to define the parameters that the HTML file will pass to your applet upon initialization. Read the text at the top of this windowit's good advise. An easy way to create a parameter is to click the
New button (located to the left of the Delete button). Each time you click the New button, a row (representing a parameter definition) with default values is added to the Parameters table. To edit an item definition, double-click the item. For example, to
change the name, double-click the name, and to change the description, double-click the description. To change the Type, after double-clicking the type, use the pull-down list box to select a valid data type. The Member variable stores the value read from
the associated <PARAM>.HTML tag.
In an early version of VJ++, the Wizard doesn't seem to check each parameter entry as valid. For example, we entered a data type of int with a value of 1.5 and, of course, we all know that 1.5 is not a valid integer. We would hope that this will be corrected in the final release; however, you should be aware of it.
You're not going to pass any parameters to NewHelloApplet. If you've experimented with creating parameters (and we hope you did), use the Delete button to remove all the parameters you created, and then click Next. (See Figure 9.5.)
Figure 9.5. A completed Step 4 of 5 window.
This window displays a free-text scrollable list box. The default information shown in the box comes from VJ++ and information you have entered to personalize your copy of VJ++. When this window first displays, all the text is selected, so be careful!
Read the message above the box to help explain why the information here can be useful. Note, the information you enter here is stored (hard coded) in the applet, not the HTML file.
Keep the default information displayed or type some new information of your own, but keep it short (Ogden Nash would probably be okay, whereas Tolstoy would not), and then click Finish. (See Figure 9.6.)
Figure 9.6. A completed Step 5 of 5 window.
This window displays the information about your new applet based upon the choices and data you provided to the Wizard. The Wizard will use the information to build the basic Java program. Pay careful attention to the names of the files that will be
created, and where the files will be located.
If you need to modify any of the information, first choose Cancel, which will redisplay the Step 5 of 5 window. From there, you can skip backwards through the windows by clicking Back. Click OK when you are ready to continue. (See Figure 9.7.)
Figure 9.7. A New Project Information window.
Once the applet has been created, click the Class View tab to display your NewHelloApplet class structure. Click the plus (+) sign to the left of the class name to expand the outline. Your NewHelloApplet class should be displayed with a plus sign to
its left. Click the plus sign to expand the outline again, and display the methods in your class.
In the Source window, at the very top of the source file, you will notice that the VJ++ Java Applet Wizard automatically added the import classes java.applet.* and java.awt.*. Remember that the * means to include all sub-libraries in the base
library (applet and awt).
If you look further down in the code windows you'll find an init() method, a destroy() method, a paint() method, and start() and stop() methods. Of all these methods, the only one with any code in it is the init() member function. The code in that
method is resize(), with two parameters (taken from the Wizard). This code resizes the applet's workspace (creates an embedded window of the specified size) within a Java-capable browser (more on that on Day 12).
There's a new method we've never discussed before in this applet: getAppletInfo. This method can be called by certain browsers when the user requests (via the browser) information about the currently running applet. You can also call this method in
your applet during a pageSetup() method. This will include your requested information prior to a print method being called. The getAppletInfo is analogous to selecting Help | About in most Windows applications.
To modify the VJ++ Java Applet Wizard's applet to resemble the HelloAgain applet created a few days ago is rather simple. First, if you look through the Source window, you won't see any references to a font object. As a result, any text drawn on the
screen will be the default color and size. Change that. In the Source window, right below the class definition line, add the following line of code:
Font fntF = new Font("TimesRoman", Font.BOLD, 36);
The section of the window should now look like the following:
public class NewHelloApplet extends Applet { Font fntF = new Font("TimesRoman", Font.BOLD, 36);
Now that you have a font object defined, you can put it to work. The paint method is where the real work of this applet (what little work there is) really occurs. The Graphics object passed into the paint() method holds the graphics state, meaning the
current features of the drawing surface. Add the following code to the paint method to complete this applet:
g.setFont(fntF); g.setColor(Color.red); g.drawString("Hello again!", 5, 50);
The paint() method should now look like the following:
public void paint(Graphics g) { g.setFont(fntF); g.setColor(Color.red); g.drawString("Hello again!", 5, 50); }
There you are! Now, compile and execute this applet. Notice how easy it is to have the VJ++ Java Applet Wizard create a skeleton applet and get it to work on a Web page. For you doubters out there, keep in mind that you didn't select multithreading or
animation. If you had, the code the Wizard would have generated would have been quite impressive.
Take a few moments to look at the HTML page that the VJ++ Java Applet Wizard created for you. You can easily find the HTML file by selecting the Files tab in the Project Workspace window.
When you compile an applet or application in Microsoft Developer Studio, errors are displayed in the Build output window located at the bottom of the screen. (Look for the Build tab.) When an error in your code is found, a line corresponding to each error displays. You can easily get to the specific line of your code that is in error by double-clicking the error line in the Build window displaying the error message. You will learn more about errors and debugging on Day 14.
Remember, applets depend upon a browser in order to function. Unlike applications, they can't run as standalone programs. Once you've created an applet, it still needs a place to exist, live, and run! The safe and nurturing environment provided by a
Web page and the HTML language allow you to let your applet go, to experience all that there is to see, and, most importantly, to be seen. The VJ++ Java Applet Wizard automatically created a simple HTML page for you. However, for testing purposes, it
included only the necessary HTML tags to execute your applet. The HTML language, though, has a lot of specific tags that do a lot of wonderful things. The rest of today we're going to expand upon the NewHelloApplet, use some of the more common HTML tags,
and show you how to make your applet available to the Web.
The following section assumes you have at least a passing understanding of writing HTML pages. If you need help in this area, you might find the book Teach Yourself Web Publishing with HTML in 14 Days useful. It is also from Sams.net.
There is a special HTML tag for including applets in Web pages; Java-capable browsers use the information contained in that tag to locate the compiled class files and execute the applet itself. In this section, you'll learn about how to put Java
applets in a Web page and how to serve those files to the Web at-large.
The <APPLET> tag is a special HTML tag used to include applets in a Web page. Java-capable browsers read this tag and then use the information contained in it to locate and execute your applet. Remember, your compiled applet will have the
extension .class, whereas its source will have the extension .Java. The <APPLET> tag references the .class file.
To include an applet on a Web page, use the <APPLET> tag. Listing 9.1 shows a very simple example of a Web page containing an applet.
Listing 9.1. A simple HTML page.
1. <html> 2. <head> 3. <title>This page has the NewHelloApplet</title> 4. </head> 5. <body> 6. <hr> 7. <applet 8. code=NewHelloApplet.class 9. width=320 10. height=240 > 11. There would be a way cool applet here if your browser supported Java 12. </applet> 13. <hr> 14. <a href="NewHelloApplet.java">The source.</a> 15. </body> 16. </html>
There are three things to note about the <APPLET> tag in the preceding HTML page:
The <APPLET> tag, like an <IMG> tag, is not in itself a paragraph, so it needs to be enclosed inside a more general text tag, such as <P>, or one of the heading tags (<H1>, <H2>, and so on).
Click the File View tab and open the .html file for your applet. Edit line 3 and add line 11 to the file so it looks like Listing 9.1. Save the changes and then execute the applet. The browser loads and parses your HTML file. When it gets to the line
containing the <APPLET> tag, it reserves the window space specified and then loads and executes the applet in that space. The only difference you should notice, because you're using a Java-enabled browser, is that a new window title displays.
Okay, you have a killer applet and you've tested it exhaustively on your local system. Everyone you've showed it to thinks you're the Web's equivalent to George Lucas. Now, how do you get the world to see your masterpiece?
Java applets are served by a Web server the same way that HTML files, images, and other media are. You don't need special server software to make Java applets available to the Web; you don't even need to configure your server to handle Java files. If
you have a Web server up and running, or space on a Web server available to you, all you have to do is move your HTML and compiled class files to that server, as you would any other file.
If you don't have a Web server, you have to rent space on one, or set one up yourself. Microsoft NT 4.0 Server and NT 4.0 Workstation both have the capability and software to be Web servers. Also, Microsoft's GUI based HTML authoring application
Frontpage, has the capability to turn a Windows NT 3.51 or 4.0 workstation into a mini-Web server suitable for a small workgroup. Please note that Web server setup and administration, as well as other facets of Web publishing in general, are outside
the scope of this book.
In its simplest form, by using CODE, WIDTH, and HEIGHT, the <APPLET> tag merely creates a space of the appropriate size and then loads and runs the applet in that space. The <APPLET> tag, however, does include several attributes that can
help you better integrate your applet into the overall design of your Web page.
The attributes available for the <APPLET> tag are almost identical to those for the HTML <IMG> tag.
The ALIGN attribute defines how the applet will be aligned in the browser window. This attribute can have one of nine values: LEFT, RIGHT, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, and ABSBOTTOM.
In the case of ALIGN=LEFT and ALIGN=RIGHT, the applet is placed at the left or right margins of the browser window, respectively, and any text outside of the applet window then flows to the left or to the right. The text will continue to flow in that
space until the bottom of the applet window, or until you use a line break tag (<BR>) with the CLEAR attribute starting the next line of text below the applet window. This is the same behavior as a desktop publishing package with an imbedded graphic,
which allows the text to wrap around the graphic or not. The CLEAR attribute can have one of three values: CLEAR=LEFT starts the text at the next clear left margin, CLEAR=RIGHT does the same for the right margin, and CLEAR=ALL starts the text at the next
line where both margins are clear.
For example, here's a fragment of HTML code that aligns an applet against the left margin, has some text flowing alongside it, and then breaks at the end of the paragraph so that the next bit of text starts below the applet:
<P><APPLET CODE="HelloAgainApplet" WIDTH=300 HEIGHT=200 ALIGN=LEFT> Hello Again!</APPLET> To the left of this paragraph is an applet. It's a simple, unassuming applet in which a small string is printed in red type, set in 36 point Times bold. <BR CLEAR=ALL> <P>In the next part of the page, we demonstrate how, under certain conditions, styrofoam peanuts can be used as a healthy snack.
Figure 9.8 shows how this applet and the text surrounding it might appear in a browser.
Figure 9.8. An applet aligned left.
For smaller applets, you might want to include your applet within a single line of text. To do this, there are seven values for ALIGN that determine how the applet is vertically aligned with the text:
Figure 9.9 shows the various alignment options, where the line is an image and the arrow is a small applet.
Figure 9.9. Applet alignment options.
The HSPACE and VSPACE attributes are used to set the amount of space, in pixels, between an applet and its surrounding text. HSPACE controls the horizontal space (the space to the left and right of the applet). VSPACE controls the vertical space (the
space above and below). For example, here's the preceding sample fragment of HTML with a vertical space of 50 and an horizontal space of 10:
<P><APPLET CODE="HelloAgainApplet" WIDTH=300 HEIGHT=200 ALIGN=LEFT VSPACE=50 HSPACE=10>Hello Again!</APPLET> To the left of this paragraph is an applet. It's a simple, unassuming applet in which a small string is printed in red type, set in 36 point Times bold. <BR CLEAR=ALL> <P>In the next part of the page, we demonstrate how, under certain conditions, styrofoam peanuts can be used as a healthy snack.
The result in a typical Java browser might look like the result in Figure 9.10.
Figure 9.10. Vertical and horizontal space.
CODE is used to indicate the name of the class file that holds the current applet. If CODE is used alone in the <APPLET> tag, the class file is searched for in the same directory as the HTML file that references it.
If you want to store your class files in a different directory than that of your HTML files, you have to tell the Java-capable browser where to find those class files. To do this, you use CODEBASE. CODE contains only the name of the class file;
CODEBASE contains an alternate pathname where classes are contained. For example, if you store your class files in a directory called /classes, which is a child directory of the directory your HTML files are in, CODEBASE would be the following:
<APPLET CODE="myclass.class" CODEBASE="classes" WIDTH=100 HEIGHT=100></APPLET>
With Java applications, you can pass parameters to your main() routine by using arguments on the command line. You can then parse those arguments inside the body of your class. The application acts accordingly, based on the arguments it is given.
Applets, however, don't have a command line. How do you pass in different arguments to an applet? Applets can get different input from the HTML file that contains the <APPLET> tag through the use of applet parameters. To set up and handle
parameters in an applet, you need two things:
Applet parameters come in two parts: a name, which is simply a name you pick, and a value, which determines the value of that particular parameter. For example, you can indicate the color of text in an applet by using a parameter with the name color
and the value red. You can determine an animation's speed using a parameter with the name speed and the value 5.
In the HTML file that contains the embedded applet, you indicate each parameter using the <PARAM> tag, which has two attributes for the name and the value called (surprisingly enough), NAME and VALUE. The <PARAM> tag goes inside the opening
and closing <APPLET> tags:
<APPLET CODE="MyApplet.class" WIDTH=100 HEIGHT=100> <PARAM NAME=font VALUE="TimesRoman"> <PARAM NAME=size VALUE="36"> A Java Applet appears here.</APPLET>
This particular example defines two parameters to the MyApplet applet: one whose name is font and whose value is TimesRoman, and one whose name is size and whose value is 36.
Parameters are passed to your applet when it is loaded. In the init() method for your applet, you can then get hold of those parameters by using the getParameter() method. getParameter() takes one argumenta string representing the name of the
parameter you're looking forand returns a string containing the corresponding value of that parameter. (Like arguments in Java applications, all the parameter values are strings.) To get the value of the font parameter from the HTML file, you might
have a line such as the following in your init() method:
String theFontName = getParameter("font");
The names of the parameters, as specified in <PARAM>, and the names of the parameters in getParameter() must match identically, including having the same case. In other words, <PARAM NAME="name"> is different from <PARAM NAME="Name">. If your parameters are not being properly passed to your applet, make sure the parameter cases match.
If a parameter you expect has not been specified in the HTML file, getParameter() returns null. Most often, you will want to test for a null parameter and supply a reasonable default:
if (theFontName == null) theFontName = "Courier"
Keep in mind that getParameter() returns strings; if you want a parameter to be some other object or type, you have to convert it yourself. To parse the size parameter from that same HTML file and assign it to an integer variable called theSize, you
might use the following lines:
int theSize; String s = getParameter("size"); if (s == null) theSize = 12; else theSize = Integer.parseInt(s);
Get it? Not yet? Try creating an example of an applet that uses this technique. You'll modify the HelloAgainApplet applet so that it says hello to a specific name, for example "Hello Jaren" or "Hello Mandy". The name is passed into
the applet through an HTML parameter.
You can begin by copying the original HelloAgainApplet class:
import java.awt.Graphics; import java.awt.Font; import java.awt.Color; public class MoreHelloApplet extends java.Applet.Applet { Font f = new Font("TimesRoman", Font.BOLD, 36); public void paint(Graphics g) { g.setFont; g.setColor(Color.red); g.drawString("Hello Again!", 5, 50); } }
The first thing you need to add to this class is a place for the name. Because you'll need that name throughout the applet, add a data member for the name, just after the variable for the font:
String name;
To set a value for the name, you have to get its corresponding parameter. You set your variables to the parameter values inside the init() method. (The VJ++ Java Applet Wizard does this automatically when you define parameters for your applet.) The
init() method is defined as public, with no arguments, and a return type of void. Make sure when you test for a parameter that you test for a null value; this way, you can supply a default value when no parameter is specified. The default, in this case, if
a name isn't indicated, is to say hello to "Trevor":
public void init() { name = getParameter("name"); if (name == null) { name = "Trevor"; } }
One last thing to do, now that you have the name from the HTML parameters, is to modify the name so that it's a complete string; that is, to tack "Hello " onto the beginning, and an exclamation point onto the end. You could do this in the
paint method just before printing the string to the screen. Here it's done only once, whereas in paint(), it's done every time the screen is repainted. In other words, it's slightly more efficient to do it inside init() instead:
name = "Hello " + name + "!";
And now, all that's left is to modify the paint() method. The original drawString() method looked like this:
g.drawString("Hello Again!", 5, 50);
To draw the new string you have stored in the name data member, all you need to do is substitute that variable for the literal string:
g.drawString(name, 5, 50);
Listing 9.2 shows the final result of the MoreHelloApplet class. Compile it so that you have a class file ready.
Listing 9.2. The MoreHelloApplet class.
1: import java.awt.Graphics; 2: import java.awt.Font; 3: import java.awt.Color; 4: 5: public class MoreHelloApplet extends java.Applet.Applet 6. { 7: Font f = new Font("TimesRoman", Font.BOLD, 36); 8: String name; 9: 10: public void init() 11: { 12: name = getParameter("name"); 13: if (name == null) 14: { 15: name = "Trevor"; 16: } 17:18: name = "Hello " + name + "!"; 19: } 20: 21: public void paint(Graphics g) 22: { 23: g.setFont; 24: g.setColor(Color.red); 25: g.drawString(name, 5, 50); 26: } 27: }
Now, create the HTML file that will start the preceding applet. Listing 9.3 shows a new Web page for the MoreHelloApplet applet.
Listing 9.3. The HTML file for the MoreHelloApplet applet.
1: <HTML> 2: <HEAD> 3: <TITLE>Hello!</TITLE> 4: </HEAD> 5: <BODY> 6: <P> 7: <APPLET CODE="MoreHelloApplet.class" WIDTH=300 HEIGHT=50> 8: <PARAM NAME=name VALUE="Jaren"> 9: Hello to whoever you are! 10: </APPLET> 11: </BODY> 12: </HTML>
Note the <APPLET> tag, which points to the class file for the applet with the appropriate width and height (300 and 50). Just below it (line 8) is the <PARAM> tag, which you use to pass in the name. Here, the NAME parameter is simply name,
and the VALUE is the string "Jaren".
Loading up this HTML file produces the result shown in Figure 9.11.
Figure 9.11. The result of MoreHelloApplet, first try.
Now try a second example. Remember that in the code for MoreHelloApplet, if no name is specified, the default is the name "Trevor". Listing 9.4 creates an HTML file with no parameter tag for name.
Listing 9.4. Another HTML File for the MoreHelloApplet applet.
1: <HTML> 2: <HEAD> 3: <TITLE>Hello!</TITLE> 4: </HEAD> 5: <BODY> 6: <P> 7: <APPLET CODE="MoreHelloApplet.class" WIDTH=300 HEIGHT=50> 8: Hello to whoever you are! 9: </APPLET> 10: </BODY> 11: </HTML>
Here, because no name was supplied, the applet uses the default, and the result is what you might expect. (See Figure 9.12.)
Figure 9.12. The result of MoreHelloApplet, second try.
Applets are probably the most common use of the Java language today. They are more complicated than many Java applications because they are executed and drawn inline within Web pages; however, they can access the graphics, user interface, and event
structure provided by the Web browser itself. Today, you learned the basics of creating applets, including the following things:
Q: In the first part of today's lesson, you say that applets are downloaded from random Web servers and run on the client's system. What's to stop an applet developer from creating an applet that deletes all the files on that system, or in some
other way compromises the security of the system?
A: Recall that Java applets have several restrictions that make it difficult for all of the more obvious malicious behavior to take place. For example, because Java applets cannot read or write files on the client system, they cannot delete
files or read system files that might contain private information. Because they cannot run programs on the client's system without your express permission, they cannot, for example, run system programs pretending to be you. Nor can they run so many
programs that your system crashes.
In addition, Java's architecture makes it difficult to circumvent these restrictions. The language itself, the Java compiler, and the Java interpreter all have checks to make sure that no one has tried to sneak in bogus code or play games with the
system itself. You'll learn more about these checks at the end of this book.
Of course, no system can claim to be 100% secure, and the fact that Java applets are run on your system should make you suspicioussee Day 21 for more on security.
Q: Wait a minute. If I can't read or write files or run programs on the system the applet is running on, doesn't that mean I basically can't do anything other than simple animation and flashy graphics?
A: For everyone who doesn't believe that Java is secure enough, there is someone who believes that Java's security restrictions are too severe for just these reasons. Yes, Java applets are limited because of the security restrictions. But given
the possibility for abuse, we believe that it's better to err on the side of being more conservative as far as security is concerned. Consider it a challenge.
Keep in mind, also, that ActiveX allows you to do more than just simple animation and graphics. We'll be discussing this on Day 21.
Q: I noticed in my documentation that the <APPLET> tag also has a NAME attribute. You didn't discuss it here.
A: NAME is used when you have multiple applets on a page that need to communicate with each other. You'll learn about this on Day 13.
Q: I have an applet that takes parameters and an HTML file that passes it to those parameters. But when my applet runs, all I get are null values. What's going on here?
A: Do the names of your parameters (in the NAME attribute) match exactly with the names you're testing for in getParameter()? They must be exact, including case, for the match to be made. Make sure, also, that your <PARAM> tags are inside
the opening and closing <APPLET> tags, and that you haven't misspelled anything.