Java Applet Basics
An Applet is a Java program. It generally runs inside a Java-supported web browser. Because it has complete Java API support, the Applet is a full-featured Java application.
The following are the important differences between a standalone Java application and an applet program:
- In Java, an Applet class inherits from the java.applet.Applet class.
- The Applet class does not define main(), so an Applet program does not call the main() method.
- Applets are designed to be embedded in an HTML page.
- When a user browses an HTML page containing an Applet, the Applet's code is downloaded to the user's machine.
- To view an Applet, a JVM is required. The JVM can be a web browser plugin, or a standalone runtime environment.
- The JVM on the user's machine creates an instance of the Applet class and calls various methods in the Applet life cycle.
- Applets have strict security rules enforced by web browsers. The Applet security mechanism is called sandbox security.
- Other classes required by the Applet can be downloaded in the form of Java Archive (JAR) files.
Applet Life Cycle
The four methods in the Applet class provide a framework on which you can develop small applets:
- init: The purpose of this method is to provide any initialization required for your Applet. This method is called after the param tags within the Applet tag have been processed.
- start:After the browser calls the init method, this method is automatically called. This method is called whenever the user returns to the page containing the Applet from another page.
- stop:This method is automatically called when the user leaves the page containing the Applet. Therefore, this method can be called repeatedly in the same Applet.
- destroy: This method is called only when the browser is closed normally. Because Applets are only valid on HTML pages, you should not leave any resources behind after the user leaves the page containing the Applet.
- paint:This method is called immediately after the start() method, or when the Applet needs to repaint in the browser. The paint() method is actually inherited from java.awt.
"Hello, World" Applet:
Below is a simple Applet program, HelloWorldApplet.java:
HelloWorldApplet.java file code:
These import statements import the following classes into our Applet class:
Without these import statements, the Java compiler cannot recognize the Applet and Graphics classes.
Applet Class
Every Applet is a subclass of the java.applet.Applet class. The base Applet class provides methods for subclasses to call in order to obtain browser context information and services.
These methods do the following:
- Get Applet parameters
- Get the network location of the HTML file containing the Applet
- Get the network location of the Applet class directory
- Print browser status information
- Fetch an image
- Fetch an audio clip
- Play an audio clip
- Resize this Applet
In addition, the Applet class provides an interface for the Viewer or browser to obtain Applet information and control the Applet execution.
The Viewer may:
- Request information about the Applet author, version, and copyright
- Request descriptions of the parameters recognized by the Applet
- Initialize the Applet
- Destroy the Applet
- Start executing the Applet
- Stop executing the Applet
The Applet class provides default implementations for these methods, which can be overridden when needed.
The "Hello, World" applet is written according to the standard. The only method overridden is the paint method.
Invoking an Applet
An Applet is a Java program. It generally runs inside a Java-supported web browser. Because it has complete Java API support, the Applet is a full-featured Java application.
The <applet> tag is the basis for embedding Applets in HTML files. The following is an example of invoking a "Hello World" applet:
HTML code:
Note:You can refer to the HTML Applet tag to learn more about how to call applets from HTML.
The attributes of the <applet> tag specify the Applet class to run. width and height are used to specify the initial size of the Applet's running panel. The Applet must be closed with the </applet> tag.
If the Applet accepts parameters, the parameter values need to be added in <param> tags, which are placed between <applet> and </applet>. The browser ignores text and other tags between the applet tags.
Browsers that do not support Java cannot execute <applet> and </applet>. Therefore, anything displayed between the tags that is unrelated to the applet is visible in browsers that do not support Java.
The Viewer or browser looks for the compiled Java code at the document location. To specify the document path, use the codebase attribute of the <applet> tag.
As shown below:
<applet codebase="http://amrood.com/applets" code="HelloWorldApplet.class" width="320" height="120">
If the Applet is in a package other than the default package, the package must be specified in the code attribute, for example:
<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120">
Getting Applet Parameters
The following example demonstrates how an Applet responds to parameters specified in a file. The Applet displays a black checkerboard pattern and a second color.
The second color and the size of each column are specified through the Applet parameters in the document.
CheckerApplet gets its parameters in the init() method. It can also get its parameters in the paint() method. However, it is convenient and efficient for the Applet to get the values at startup and save the settings, rather than getting the values on every refresh.
The Applet viewer or browser calls the init() method every time the Applet runs. After loading the Applet, the Viewer immediately calls the init() method (Applet.init() does nothing). Override the default implementation of this method to add custom initialization code.
The Applet.getParameter() method gets the parameter value by the parameter name. If the obtained value is a number or other non-character data, it must be parsed from the string type.
The following example is a modification of CheckerApplet.java:
CheckerApplet.java file code:
Below are the init() method and the private parseSquareSize() method of the CheckerApplet class:
The Applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a string into an integer. When the parameter is invalid, Integer.parseInt() throws an exception.
Therefore, the parseSquareSize() method also catches exceptions and does not allow the Applet to accept invalid input.
The Applet calls the parseColor() method to parse the color parameter into a Color value. The parseColor() method performs a series of string comparisons to match the parameter value against predefined color names. You need to implement these methods to make the Applet work.
Specifying Applet Parameters
The following example is an HTML file that embeds the CheckerApplet class. The HTML file specifies two parameters for the applet by using the <param> tag.
Note:Parameter names are case-insensitive.
Converting an Application to an Applet
Converting a graphical Java application (that is, an application that uses AWT and is launched with the java program launcher) into an applet embedded in a web page is simple.
The following are the steps to convert an application into an Applet:
- Write an HTML page that contains a tag that can load the applet code.
- Write a subclass of the JApplet class and make the class public. Otherwise, the Applet cannot be loaded.
- Remove the application's main() method. Do not construct a frame window for the application, because your application is to be displayed in the browser.
- Move the initialization code from the frame window constructor in the application into the Applet's init() method. You do not need to explicitly construct the Applet object; the browser will instantiate an object by calling the init() method.
- Remove the call to the setSize() method. For an Applet, the size is already set by the width and height parameters in the HTML file.
- Remove the call to the setDefaultCloseOperation() method. An Applet cannot be closed; it terminates when the browser exits.
- If the application calls the setTitle() method, remove that call. An applet cannot have a title bar. (Of course, you can name the web page itself using the HTML <title> tag.)
- Do not call setVisible(true); the Applet is displayed automatically.
Event Handling
The Applet class inherits many event handling methods from the Container class. The Container class defines several methods, such as processKeyEvent() and processMouseEvent(), for handling specific types of events, as well as a catch-all event method called processEvent.
To respond to an event, the Applet must override the appropriate event handling method.
ExampleEventHandling.java file code:
Invoke the Applet as follows:
When it first runs, the Applet displays "initializing the applet. Starting the applet." Then, as soon as you click the rectangle, it displays "mouse clicked".
Displaying Images
An Applet can display images in GIF, JPEG, BMP, and other formats. To display an image in an Applet, you need to use the drawImage() method of the java.awt.Graphics class.
The following example demonstrates all the steps for displaying an image:
ImageDemo.java file code:
Invoke the applet as follows:
Playing Audio
An Applet can play audio by using the AudioClip interface in the java.applet package. The AudioClip interface defines three methods:
- public void play():Play the audio clip once from the beginning.
- public void loop(): Loop the audio clip.
- public void stop(): Stop playing the audio clip.
To obtain an AudioClip object, you must call the getAudioClip() method of the Applet class. This method returns immediately regardless of whether the URL points to a real audio file.
The audio file is downloaded only when it is about to be played.
The following example demonstrates all the steps for playing audio:
AudioDemo.java file code:
Invoke the applet as follows:
You can use test.wav on your computer to test the above example.
Other Extensions