One of the major uses of Java is the creation of miniapplications, or applets, which are designed to be small, fast, and easily transferable over network resources. These applets can be thought of as small programs that might be more focused in scope than a full-blown application. For example, an application might be a spreadsheet. A full-blown spreadsheet would enable users to specify a variety of calculations and functions, from amortizing loans to keeping fullfinancial records for a small business. An applet, on the other hand, might be limited to a loan calculator, figuring interest and loan payments. Rather than trying to do it all, like anapplication, applets generally focus on one small task or a component of a task. Instead ofbeing limited and narrow, applets are streamlined and more efficient.
Quite simply, applets are compiled Java programs that are run using the Applet Viewer or through any World Wide Web browser that supports Java. What an applet does is up to you. It can display graphics, play sounds, accept user input, and manipulate data just like any program. This section is designed to help you understand what goes into creating an applet and how applets can function in conjunction with the Internet and the World Wide Web.
Technically an applet is a subclass of java.awt.Panel. Being such, an applet can contain features from the Abstract Window Toolkit and the Java Language Package. To aid in the creation of applets, Sun also has developed the Java Applet Package, a collection of constructs and methods designed to make a number of useful features accessible to programmers.
Applets were not conceived for use with the Internet, instead they were designed for use with hand-held computing devices, or Personal Digital Assistants. However, the basic properties of applets have made them a perfect fit for use on the Internet and the World Wide Web. Because applets are small, they are downloaded and launched very quickly. Applets can add new levels of functionality and interactivity to Web pages without the overhead of full-scale applications. With the recent introduction of Java-capable browsers such as Netscape, applets have begun to make a serious impact on the World Wide Web.
More Web pages are now featuring Java applets for a variety of uses. Some of the ways applets are currently being used on the World Wide Web include the following:
Java applets take special advantage of the features already built into Web browsers, enabling programmers to obtain a rich feature set with a minimum of code. For example, to incorporate GIF or JPEG files into a Java applet, it is not necessary to write any decoding methods for the image files. Applets can use the browsers decoder to display image files. Using the browser to display images makes applets easily extensible. If a new image format becomes popular and is incorporated into a browser, the Java applet will automatically be able to handle that format. It isnt necessary for the applet programmer to change the applet significantly to access new formats. Applets are well-suited to the World Wide Web because they leverage browser features to decrease size, increase download speed, and simplify applet programming.
Applets can be quite robust programs; however, there are significant differences between applets and applications. Applets are not full-featured applications. There are concrete and implicit limitations that need to be considered in designing and creating applets. For example:
Weve already described how applets leverage Web browsers to provide functionality over applications. However, the nature of applets warrants some important restrictions on their functionality in the interest of security.
Because applets can be downloaded over the Web, they are, by nature, not secure. Applets are precompiled bytecode. The compiled bytecode is downloaded to your machine and executed locally. Because of this, both Sun and browser manufacturers have placed some restrictions on the functionality of applets. Unfortunately, while these restrictions limit what an applet iscapable of, they are not meant to hinder the development of applets. Instead, theserestrictions are meant to ensure the security of machines that will run applets by preventing applets from being used maliciously. This security was implemented to help them gain wide acceptance on the Net.
Applets are downloaded from their home servers as bytecode. This is what makes Java easily portable from platform to platform. The bytecode is platform-independent, and is executed through the Applet Viewer or a Java-capable Web browser. Because the bytecode is executed on a users local machine, there needs to be some level of security to make sure that the integrity of the machine is not compromised.
One of the ways that Java accomplishes this is through a verification process to ensure that the bytecode does not violate any Java language conventions. In order to perform verification, any methods or variables must be called by name. Calling methods by name allows verification of all the methods and variables in the bytecode, and ensures that an applet is not accessing memory areas that might contain the OS or other applications. Limiting functions to call-by-name also has the advantage of eliminating memory pointers, and anyone who has struggled with pointers in C or C++ can testify that pointers are one of the most commonly misunderstood aspects of programming. The elimination of pointers is not without a priceimplementing all methods and variables by name slows down Java applets when compared to other programming languages.
Applets are not given full access to the local machines file system. Applets currently do not have the means to save files out to a users local machine, and they cant read files off the local machine either. Though this does limit the functionality of applets significantly, allowing applets access to a local file system would represent a serious security hole. For example, if an applet could read files on a system, it could potentially send information from those files back to the applets author. If an applet could write files to a system, it could potentially become a carrier for viruses. Rather than risk security, applets are simply prevented from accessing files. Undoubtedly, file access would increase the functionality of applets and the end goal is to allow applets to read and save files. There are various ways this might be accomplished, but until more security methods are implemented, applets are prevented from file system access.
Applets also are restricted from loading dynamic or shared libraries from other programming languages. Java has the capability to declare methods as being native, which allows the virtual machine to take advantage of other language libraries such as C or C++. However, because these libraries cant be verified and they would require access to the file system, applets are not allowed to use dynamic libraries. The end goal is to optimize Java to the point where all of the dynamic libraries could be written in Java and the need for other language libraries would be eliminated. As the language grows and evolves, many of these limitations will be removed. For now, they are the price of participating so closely in the evolution of a new language.
In addition to the limitations imposed by the language itself, the browser that executes applet bytecode also places some restrictions on applets. A Web browser is a trusted applicationa user has chosen to load the browser on the local machine and trusts that it will not damage any files or the operating system. Applets are untrusted applications. They are downloaded immediately and are executed on a machine without receiving the users consent. (The user might choose to use a Java-capable browser, and therefore imply consent, but the user cant approve individual applets.) Because of this, Java-capable browsers have placed some restrictions on applets in order to ensure that they dont violate system integrity inadvertently.
The most important limitation placed on an applet by the Web browser is network connectivity. Applets currently are limited to network connections with their host machines. This means your Java applet can communicate directly back to the Web server that its downloaded from, but it cannot contact any other servers on the Net. Networking also comes back to the issue of security. By restricting access back to the applets original host, applets are provided basic network functionality with a minimum security risk. If applets were allowed to contact any server on the Net, applets could perform some potentially dangerous tasks.
For example, if an applet was allowed to contact any server, it would be possible to make a connection to any e-mail server. An applet could then masquerade as your machine and send forged mail that would appear to be coming from you. The issue of network connectivity for applets is widely debated among Java developers. It is still possible to write a number of applets that take advantage of network connections to their own servers. Though restricting network connectivity imposes some limits on applets, it is being done in the interest of security. Certainly, as better security methods are developed, network connectivity will increase and applets will become more functional. For more information on Java security issues, see Chapter 40.
The object-oriented nature of Java is instrumental in understanding what defines an applet from a technical standpoint. Because of the hierarchy of the Java classes, an applet is an extension of the Panel object in the Abstract Windows Toolkit (AWT). A panel is a subclass of the Container class (see Figure 21.1), and as such can contain any Java language components, such as buttons, menus, scroll bars, and so on.
Because an applet actually is a class, applets can be used to build other applets or full-blown applications. Just as your applets can be used within other applets, they also inherit features from the classes above them.
Applets also have distinct stages in their lifetime. These stages include init, start, stop, and destroy. All of these methods can be overwritten by the applet programmer to accomplish specific tasks during each stage in an applets lifetime.
FIGURE 21.1.The Java class hierarchies.
Here is a breakdown of the four stages:
init();
The init stage consists of initializing any methods and variables the applet needs to function, such as images to be loaded. The init method is called when the applet is first loaded.
start();
The start stage starts the primary functions of an applet. For example, if an applet plays a sound, it could start playing during the start stage. The start method is called when the init method has finished and the applet is ready to execute.
stop();
The stop stage can be used to stop any actions that might still be in progress from the start stage when an applet is exited. For example, a sound loop would need to be stopped when a person left the Web page containing a sound applet. The stop method is called when the page is left, or the browser is minimized.
destroy();
Destroy is called automatically, and completes any memory cleanup or garbage collection that needs to be done when an applet is destroyed. It can be overwritten, but this is not generally necessary. The destroy method is called when you quit a browser.
Applets inherit the properties of the Panel object in the AWT, and the Applet class attributes from java.applet.Applet. This is evident in the way that all Java applets are structured. In defining the initial applet,
public class Classname extends java.applet.Applet { }
the code shows how your applet class is an extension of the Applet class. There are a number of methods that are built into the Applet class to make developing applets easier and these are the subject of Chapter 23, The Applet Package and Graphics.
The idea of inheritance is fundamental to the structure of applets. Applets inherit thecapability to contain user interface objects because all applets are Panels. Applets inherit a great deal of their functionality from the Applet class.
Applets currently can be viewed on several UNIX platforms, Windows 95, and Windows NT. The Java world is continuing to expand, and soon Java will be available for more popular platforms. Once your Java code has been compiled, it can be executed with the Applet Viewer, or through any Java-capable browser. Applets require the following two components to execute:
The compiled bytecode is the executable component of the applet. The HTML file is required by both the Applet Viewer and any Web browser in order to execute the code properly. The HTML file is based on the <applet> tag and takes the following basic structure:
<html> <applet codebase=location of code code=filename.class width=100 height=150 alt=alternate> <param name=parameter value=accepted value> </applet> </html>
The <applet> tag contains the filename of your executable code, in the format of filename.class, followed by the dimensions of your applet. The initial dimensions of the applet need to be given in pixels. This is because the applet has to fit into the conventions of HTML page layout. The <param> tag accepts the parameter name and its associated value. The parameter tag is only necessary if the applet is designed to take parameters, and it can be repeated as many times as necessary to establish the parameter values. Here is a list of the tags and values that can be used in an applet HTML file:
param
The parameter tag also takes name and value tags to specify the values for any parameters an applet accepts (see the preceding HTML example).
The following are actually parameters to the <applet> tag, and are used to give the browser information about the applet itself.
codebase
The codebase is the base URL location of the Java bytecode. This enables you to have your code in a different directory than the page your applet appears on.
alt
Identical to the HTML <alt> tag, this tag enables you to provide an alternate image or text for Web browsers that are not Java-capable. Alternate options can also be specified by placing HTML code between the <applet> and </applet> tags.
name
The <name> tag enables you to specify a symbolic name for an applet. The name is used as a reference to communicate by other applets on the same page.
align
Identical to the standard HTML <align> tag. This tag enables you to specify right, left, or center alignment of your applet.
vspace and hspace
These tags enable you to specify the amount of vertical and horizontal space around an applet when it is aligned to the left or right with the <align> tag.
code
The code parameter is required with the <applet> tag. It specifies the location of the actual compiled applet.
width
The width parameter is used with the <applet> tag to specify the width of the window that should be opened when the applet is added to the page. It is required by the <applet> tag.
height
The height parameter is similar to width, specifying the height of the applet window. It is also required.
The following applet example is called Speaker. It displays a static graphic image and plays an audio file.
/* Speaker This applet displays a gif or jpeg while playing a sound (.au) file. */ import java.awt.*; import java.applet.*; import java.lang.*; import java.net.URL; public class Speaker extends java.applet.Applet { Image image; AudioClip sound; String graphic; String clip; public String[][] getParameterInfo() { String[][] info = { {graphic, string, The image file to be displayed.}, {clip, string, The sound file to be played.}, }; return info; } public void init() { graphic = getParameter(graphic); clip = getParameter(clip); image = getImage(getDocumentBase(), graphic); sound = getAudioClip(getDocumentBase(), clip); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } public void start() { repaint(); // This could also be sound.loop(); to loop the sound. sound.play(); } public void stop() { sound.stop(); } }
Because of the nature of this applet, the user interface is fairly limited. It doesnt accept interactive input from users, so it really isnt necessary to include elements from the AWT. For the purpose of starting with an applet in its most simple form, this applet does not deal with issues of user input or event handling. Those topics are covered later in this section in Chapter 22, The Windowing Package. However, if the image and sound file were hard-coded, it would seriously impair the general usefulness of this applet.
In order to make this a functional applet, Speaker is designed to accept the image file and sound file from parameters specified in the <applet> tag. Parameters are a function of user interface. They enable the user to specify changeable elements of an appletin this case the image and the sound. The following code allows the Speaker applet to read parameters and convert them into variables for use:
public String[][] getParameterInfo() { String[][] info = { {graphic, string, The image file to be displayed.}, {clip, string, The sound file to be played.}, }; return info; } public void init() { graphic = getParameter(graphic); clip = getParameter(clip); image = getImage(getDocumentBase(), graphic); sound = getAudioClip(getDocumentBase(), clip); }
The applet is passed the information from the HTML file and enters that information in an array where it can be queried by other methods, such as getParameter(). Using getParameter, the applet can use the user-provided filenames to load the image file and the sound file.
The overall design of this applet is very simple. Once the parameters are parsed, it is only a matter of downloading the image and sound files and displaying them.
To download the files, the applet uses getImage() and getAudioClip() from the Applet Package. The image files can be either GIF or JPEG files. Because applets are capable of displaying either format with the same method, it isnt necessary to specify what type of image the files are. The same is true with the sound file. Applets only can deal with sound in the AU format right now, so dealing with file information is easy.
public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } public void start() { repaint(); sound.play(); } public void stop() { sound.stop(); }
As you can see, it does not take a ton of Java code to make some great enhancements to your Web pages. With a few short lines of code you can add graphics and sound easilyjust by linking an applet to your pages with a few lines of HTML. Now that you have an idea about the basic workings of applets, well move on to some more advanced topics to help you program applets with a broader range of features and functionality.
The following outlines the basic tools for creating your own applets.
Chapter 22, The Windowing Package, covers the Abstract Window Toolkit. The AWT enables you to create user interfaces for your applets and create key components such as buttons and text fields. The chapter also covers event handling and other components important in the creation of interactive applets.
Chapter 23, The Applet Package and Graphics, discusses some of the features that are included in the Applet Package. It covers some aspects of applet control, the structure of applets, and methods included in the Applet Package.
Chapter 24, Programming Applets, wraps up the discussion of applets with some practical examples of assembling your own applets. This chapter builds some applets from the ground upfrom user interfaces to data structures.
Unfortunately, even with this comprehensive coverage, there are still many aspects of Java and applet programming that will not be covered. This section tries to cover all of the basic topics needed to get you started and enough advanced topics to get you programming robust,feature-rich applets. Java is a full-featured programming language and undoubtedly thesubject of applet programming could fill an entire book on its own. Java is also in a constant state of evolution. As the language becomes more complete, changes will be made. In order to learn about all of the necessary changes, updates, and features that could not be covered here, you should consult the official Sun documentation of the Java language. Most of the API and other Java-related documentation can be found at http://www.javasoft.com. Keep in mind that the Sun documentation is quite technical and often requires an advanced understanding of Java, but as a technical reference source it can be invaluable.