APPLETS An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). For information and examples on how to include an applet in an HTML page, refer to this description of the <APPLET> tag. Using the APPLET Tag : This section tells you most of what you need to know to use the <APPLET> tag. It starts by showing you the tag's simplest form. It then discusses some of the most common additions to that simple form: the
tag, alternate HTML code and text, the CODEBASE attribute, and the ARCHIVE attribute. You should already have seen the simplest form of the <APPLET> tag: <APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt> This tag tells the browser to load the applet whose Applet subclass is named AppletSubclass, displaying it in an area of the specified width and height. Specifying Parameters. Some applets let the user customize the applet's configuration with parameters. For example, AppletButton (an applet used throughout this tutorial to provide a button that brings up a window) allows the user to set the button's text by specifying the value of a parameter named BUTTONTEXT. The user specifies the value of a parameter using a
tag. The
tags should appear just after the <APPLET> tag for the applet they affect: <APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>
Here's an example of the
tag in use. <APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160>
...
Specifying Alternate HTML Code and Text: Note the ellipsis points (". . .") in the previous HTML example. What did the example leave out? It omitted alternate HTML code -- HTML code interpreted only by browsers that don't understand the <APPLET> tag. Alternate HTML code is any text that appears between the <APPLET> and tags, after any
tags. Java-enabled browsers ignore alternate HTML code. To specify alternate text to Java-enabled browsers and other browsers that understand the <APPLET> tag, use the ALT attribute. If the browser can't display an applet for some reason, it can display the applet's ALT text. We use alternate HTML code throughout the online version of this tutorial to tell readers about the applets they're missing. Often, the alternate HTML code includes one or more pictures of the applet. Here's the complete HTML code for the Animator example shown previously: <APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160 ALT="If you could run this applet, you'd see some animation">
Your browser is completely ignoring the <APPLET> tag! An applet that doesn't understand the <APPLET> tag ignores everything in the previous HTML code except the line that starts with "Your". A browser that does understand the <APPLET> tag ignores everything on that line. If the applet-savvy browser can't run the applet, it might display the ALT text. Specifying the Applet Directory By default, a browser looks for an applet's class and archive files in the same directory as the HTML file that has the <APPLET> tag. (If the applet's class is in a package, then the browser uses the package name to construct a directory path underneath the HTML file's directory.) Sometimes, however, it's useful to put the applet's files somewhere else. You can use the CODEBASE attribute to tell the browser in which directory the applet's files are located: <APPLET CODE=AppletSubclass.class CODEBASE=aURL WIDTH=anInt HEIGHT=anInt>
If aURL is a relative URL, then it's interpreted relative to the HTML document's location. By making aURL an absolute URL, you can load an applet from just about anywhere -even from another HTTP server. This tutorial uses CODEBASE="someDirectory/" frequently, since we group the examples for each lesson in subdirectories. For example, here's the <APPLET> tag that includes the Simple applet in LIFE CYCLE of An APPLET <APPLET CODE=Simple.class CODEBASE="example/" WIDTH=500 HEIGHT=20> The following figure shows the location of the class file, relative to the HTML file, when CODEBASE is set to "example/".
The next figure shows where the applet class can be if you specify an absolute URL for the value of CODEBASE.
Combining an Applet's Files into a Single File If your applet has more than one file, you should consider providing an archive file that bundles the applet's files into a single file. Whether archive files make sense for your applet depends on several factors, including your applet's size, performance considerations, and the environment you expect your users to have. Archive files reduce your applet's total download time. Much of the time saved comes from reducing the number of HTTP connections that the browser must make. Each HTTP connection can take several seconds to start. This means that for a multifile applet, connection time can dwarf transfer time. You can further reduce transfer time by compressing the files in your archive file. If you specify one or more archive files, then the browser looks for the archive files in the same directory that it would search for the applet class file. The browser then looks for the applet's class files in the archive files. If a file isn't in the archive, then the browser generally tries to load it just as it would if the archive file weren't present. The standard Java archive format, called JAR, was introduced in JDK 1.1 and is based on the ZIP file format. You specify JAR files using the ARCHIVE attribute of the <APPLET> tag. You can specify multiple archive files by separating them with commas: <APPLET CODE="AppletSubclass.class" ARCHIVE="file1, file2"
WIDTH=anInt HEIGHT=anInt> Unfortunately, not all browsers understand the same archive format or use the same HTML code to specify the applet archive. Watch this page for the latest information about browser support for archives. Other <APPLET> Tag Attributes This section didn't discuss every attribute of the <APPLET> tag. Other attributes -- which might seem familiar, since the
HTML tag uses them -- include ALIGN, VSPACE, and HSPACE. The <APPLET> tag also allows you to load a serialized (saved) applet by specifying the OBJECT attribute instead of specifying a class file with CODE. Finally, you can name an applet using the NAME attribute. The Life Cycle of an Applet Below is the Simple applet. Below is the source code for the Simple. The Simple applet displays a descriptive string whenever it encounters a major milestone in its life, such as when the user first visits the page the applet's on. The pages that follow use the Simple applet and build upon it to illustrate concepts that are common to many applets. * Java SE 5 Version */ import java.applet.Applet; import java.awt.Graphics; //No need to extend JApplet, since we don't add any components; //we just paint. public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); }
public void destroy() { addItem("preparing for unloading..."); } private void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); //Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } } Note: In this example, we extend the Applet class, not the Swing JApplet class, as we do not need to add Swing components to this applet. Loading the Applet You should see "initializing... starting..." above, as the result of the applet being loaded. When an applet is loaded, here's what happens: An instance of the applet's controlling class (an Applet subclass)is created. The applet initializes itself. The applet starts running. Leaving and Returning to the Applet's Page When the user leaves the page — for example, to go to another page — the browser stops the applet. When the user returns to the page, the browser starts the applet. Browser note: Some browsers reload the applet when you return to its page. In at least one browser, a bug exists where an applet can initialize itself more than once without being reloaded. Reloading the Applet Some browsers let the user reload applets, which consists of unloading the applet and then loading it again. Before an applet is unloaded, it's given the chance to stop itself and then to perform a final cleanup, so that the applet can release any resources it holds. After that, the applet is unloaded and then loaded again, as described in Loading the Applet, above. Try this: If your browser or other applet viewer lets you easily reload applets, reload the applet. Look at the standard output to see what happens when you reload the applet. (See Displaying Short Status Strings for information about the standard output.) You should see "stopping..." and "preparing for unloading..." when the applet is unloaded. You can't see this in the applet GUI because the applet is unloaded before the text can be displayed.
When the applet is reloaded, you should see "initializing..." and "starting...", just like when you loaded the applet for the first time. Quitting the Browser When the user quits the browser (or whatever application is displaying the applet), the applet has the chance to stop itself and do final cleanup before the browser exits. Summary An applet can react to major events in the following ways: It can initialize itself. It can start running. It can stop running. It can perform a final cleanup, in preparation for being unloaded. The next page describes the four applet methods that correspond to these four types of reactions. Methods for Milestones ( Life Cycle of an Applet) The Simple applet, like every other applet, features a subclass of the Applet class. The Simple class overrides four Applet methods so that it can respond to major events: init To initialize the applet each time it's loaded (or reloaded). start To start the applet's execution, such as when the applet's loaded or when the user revisits a page that contains the applet. stop To stop the applet's execution, such as when the user leaves the applet's page or quits the browser. destroy To perform a final cleanup in preparation for unloading. Following is the interface for these methods: public class Simple extends JApplet { ... public void init() { . . . } public void start() { . . . } public void stop() { . . . } public void destroy() { . . . } ... } The init, start, stop, and destroy methods are discussed and used throughout this tutorial. Overriding These Methods Not every applet needs to override every one of these methods. Some very simple applets override none of them. For example, the HelloWorld applet at the beginning of this
section doesn't override any of these methods, since it doesn't do anything except draw itself. The "Hello World" applet just displays a string once, using its paint method. (The paint method is described on the following page.) Most applets, however, do more. The init Method The init method is useful for one-time initialization that doesn't take very long. In general, the init method should contain the code that you would normally put into a constructor. The reason applets shouldn't usually have constructors is that an applet isn't guaranteed to have a full environment until its init method is called. For example, the Applet image loading methods simply don't work inside of an applet constructor. The init method, on the other hand, is a great place to call the image loading methods, since the methods return quickly. Browser note: Some browsers sometimes call the init method more than once after the applet has been loaded. The start Method Every applet that does something after initialization (except in direct response to user actions) must override the start method. The start method either performs the applet's work or (more likely) starts up one or more threads to perform the work. You'll learn more about threads later in this trail, in the Threads in Applets section. You'll learn more about handling the events that represent user actions on the next page. The stop Method Most applets that override start should also override the stop method. The stop method should suspend the applet's execution, so that it doesn't take up system resources when the user isn't viewing the applet's page. For example, an applet that displays animation should stop trying to draw the animation when the user isn't looking at it. The destroy Method Many applets don't need to override the destroy method, since their stop method (which is called before destroy) does everything necessary to shut down the applet's execution. However, destroy is available for applets that need to release additional resources. Note: You should keep implementations of the destroy method as short as possible, because there is no guarantee that this method will be completely executed. The Java Virtual Machine might exit before a long destroy method has completed.
Taking Advantage of the Applet API The applet API lets you take advantage of the close relationship that applets have with Web browsers. The API is provided by the javax.swing.JApplet class and the java.applet.AppletContext interface. Applets can use these APIs to do the following:
• • • • • • •
Be notified by the browser of milestones. Load data files specified relative to the URL of the applet or the page in which it is running. Display short status strings. Make the browser display a document. Find other applets running in the same page. Play sounds. Get parameters specified by the user in the <APPLET> tag.
Deploying Applets This section explains to HTML authors how and when to use the applet, object, and embed tags to add Java applets to Web pages, and provides guidelines for deploying applets on the Internet and Intranets, and for use with different browsers. •
Deploying Applets on the Internet Versus an Intranet
When deploying applets: Use the applet tag if the Web page is accessed through the Internet, or if it is accessed through an Intranet in which people use different browsers. Use the object or embed tag if the Web page is accessed through an Intranet and you know which browser people use. •
Deploying Applets for Specific Browsers
When deploying applets: For Internet Explorer only, use the object tag. For the Mozilla family of browsers only, use the embed tag. •
You use the applet tag to deploy applets to a multi-browser environment.
•
You use the object tag to deploy applets that are to be used only with Internet Explorer.
•
You use the embed tag to deploy applets that are to be used only with the Mozilla family of browsers.
Questions and Answers: Java Applets Question: Which classes can an applet extend? Answer: An applet can extend the java.applet.Applet class or the java.swing.JApplet class.
The java.applet.Applet class extends the java.awt.Panel class and enables you to use the GUI tools in the AWT package. The java.swing.JApplet class is a subclass of java.applet.Applet that also enables you to use the Swing GUI tools. Question: How do you cause the applet GUI in the browser to be refreshed when data in it may have changed? Answer: You invoke the repaint() method. This method causes the paint method, which is required in any applet, to be invoked again, updating the display. Question: For what do you use the start() method? Answer: You use the start() method when the applet must perform a task after it is initialized, before receiving user input. The start() method either performs the applet's work or (more likely) starts up one or more threads to perform the work. Question: True or false: An applet can make network connections to any host on the Internet. Answer: False: An applet can only connect to the host that it came from. Question: How do you get the value of a parameter specified in the APPLET tag from within the applet's code? Answer: You use the getParameter("Parameter name") method, which returns the String value of the parameter. Question: True of false: An applet can run multiple threads. Answer: True. The paint and update methods are always called from the AWT drawing and event handling thread. You can have your applet create additional threads, which is recommended for performing time-consuming tasks. Question: Match the following tag names with the descriptions in the following lists: EMBED tag APPLET tag OBJECT tag Use to deploy applets to a multi-browser environment. Use to deploy applets that are to be used only with the Mozilla family of browsers Use to deploy applets that are to be used only with Internet Explorer Answer: EMBED tag: b APPLET tag: a OBJECT tag: c Exercise: For an applet using the Exercise class, write the Applet tag that sets the ButtonName parameter to Save. Answer: <APPLET CODE=AppletButton.class>
Exercise: Write the method to display an applet in the browser, so that the contents are contained in a rectangle around the phrase "Exercise Applet". Have the applet be one pixal less than the size specified ont he web page, and the phrase starting at the coordinates 5, 15. Answer: public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); //Draw the current string inside the rectangle. g.drawString("Exercise Applet", 5, 15); } Additional information about applets: Programs written in Java are called applets. The first browser that could show applets was introduced in 1994, as "WebRunner" - later known as "The HotJava Browser". You do not need to know Java to install applets on your pages. There are thousands of free applets available on the internet for almost any purpose. Most of them can be customized without programming. Most of today's browsers can run applets. The ones that can't, aren't of much importance, since very few users have such outdated browsers. To be more precise, applets can be embedded in pages viewed by Netscape 2+ and Internet Explorer 3+. However, some people have turned off the ability to run applets in their browser. This is in most cases companies with more or less paranoid ideas of potential hacking. No matter what their motivation is, it's a fact that there are a minor amount of people out there, that will not see your applets, even if their browser is capable of showing it. This should be taken into consideration before deciding to add applets to your pages. An applet can be embedded into a webpage. Usually the applet has several settings that will allow you to personalize it. For instance, if you insert an applet that will work as a menu, you can specify which options should be in the menu, and which pages should be loaded upon click on an option. Since Java is a real programming language there aren't many limitations to it. Any program running on your computer could possibly have been made as an applet. Spreadsheets, wordprocessors, graphics programs... even entire browsers could be made with Java. However, most applets used on webpages serve much smaller purposes than
the ones mentioned. The reason is simple: They need to be transferred through the internet, and therefore can't take up just any amount of space.