Applets in Java
Applets in Java
A Java applet is a special kind of Java program that a browser enabled with Java technology
can download from the internet and run. An applet is typically embedded inside a web page
and runs in the context of a browser. An applet must be a subclass of
the java.applet.Applet class. The Applet class provides the standard interface between the
applet and the browser environment.
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as part of a web
document.
After a user receives an applet, the applet can produce a graphical user interface. It
has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
Any applet in Java is a class that extends the java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The JVM
can use either a plug-in of the Web browser or a separate runtime environment to run an
applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.
1
Given the fact that Java applets can be downloaded from anywhere and run on a client’s
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 trojan horses (programs that seem friendly but do some sort of damage to the
system), or be used to compromise the security of the system that runs them. The restrictions
on what an applet can do include the following:
Applets can’t read or write to the reader’s file system, except in specific directories
(which are defined by the user through an access control list that, by default, is
empty). Some browsers may not even allow an applet to read or write to the file
system at all.
Applets can’t usually communicate with a server other than the one that had
originally stored the applet. (This may be configurable by the browser; however, you
should not depend on having this behavior available.)
Applets can’t run any programs on the reader’s system. For Unix systems, this
includes forking a process.
Applets can’t load programs native to the local platform, including shared libraries
such as DLLs.
There are two varieties of applets; the first are those based directly on the Applet class. These
applets use the Abstract Window Toolkit (AWT) to provide the graphical user interface (or
use no GUI at all). This style of applet has been available since Java was first created.
The second type of applets are those based on the Swing class JApplet, which inherits
Applet. Swing applets use the Swing classes to provide the GUI. Swing offers a richer and
often easier-to-use user interface than does the AWT. Thus, Swing-based applets are now the
most popular. However, traditional AWT-based applets are still used, especially when only a
very simple user interface is required. Thus, both AWT- and Swing-based applets are valid.
AWT-based applets are subclasses of Applet. Applets are not stand-alone programs. Instead,
they run within either a web browser or an applet viewer.
Execution of an applet does not begin at main( ). Instead, execution of an applet is started
and controlled with an entirely different mechanism. Output to your applet’s window is not
performed by System.out.println( ). Rather, in an AWT-based applet, output is handled with
various AWT methods, such as drawString( ), which outputs a string to a specified X,Y
location. Input is also handled differently than in a console application.
How Applets and Applications Are Different
Java applications are stand-alone Java programs that can be run by using just the Java
interpreter, for example, from a command line.
Java applets are run from inside a Web browser. A reference to an applet is embedded
in a Web page using a special HTML tag. When a reader, using a Java-enabled
browser, loads a Web page with an applet in it, the browser downloads that applet
from a Web server and executes it on the local system (the one the browser is running
on).
2
Because Java applets run inside the Java browser, they have access to the same
capabilities that the browser has: sophisticated graphics, drawing, and image
processing packages; user interface elements; networking; and event handling.
An Applet class does not have any main() method. It is viewed using JVM. The JVM
can use either a plug-in of the Web browser or a separate runtime environment to run
an applet.
init: This method is intended for whatever initialization is needed for an applet.
start: This method is automatically called after init method. It is also called whenever
user returns to the page containing the applet after visiting other pages.
stop: This method is automatically called whenever the user moves away from the
page containing applets. This method can be used to stop an animation.
destroy: This method is only called when the browser shuts down normally.
Every Applet needs to implement one or more of the init(), the start( ) and the paint( )
methods.
At the end of the execution, the stop( ) method is invoked, followed by the destroy( )
method to deallocate the applet’s resources.
Initialization
Initialization occurs when the applet is first loaded (or reloaded). Initialization can include
creating the objects it needs, setting up an initial state, loading images or fonts, or setting
parameters. To provide behavior for the initialization of your applet, override the init()
method:
3
}
Starting
After an applet is initialized, it is started. Starting can also occur if the applet was previously
stopped. For example, an applet is stopped if the reader follows a link to a different web page,
and it is started again when the reader returns to this page. Note that starting can occur
several times during an applet’s life cycle, whereas initialization happens only once. To
provide startup behavior for your applet, override the start() method:
public void start() {
...
}
Functionality that you put in the start() method might include starting up a thread to control
the applet, sending the appropriate messages to helper objects, or in some way telling the
applet to begin running.
Stopping
Stopping occurs when the reader leaves the web page that contains a currently running applet.
By default, when the reader leaves a page, the applet continues running, using up system
resources. By overriding stop, you can suspend execution of the applet and then restart it if
the applet is viewed again. To stop an applet’s execution, use the stop() method:
public void stop() {
...
}
Destroying
Destroying enables the applet to clean up after itself just before it or the browser exits—for
example, to kill any running threads or to release any other running objects. Generally, you
won’t want to override destroy unless you have specific resources that need to be released—
for example, threads that the applet has created. To provide clean up behavior for your applet,
override the destroy() method:
Painting
Painting is how an applet actually draws something on the screen, be it text, a line, a colored
background, or an image. Painting can occur many hundreds of times during an applet’s life
cycle—for example, once after the applet is initialized, if the browser is placed behind
another window on the screen and then brought forward again, if the browser window is
moved to a different position on the screen, or perhaps repeatedly in the case of animations.
You override the paint() method for your applet to have an actual appearance on the screen.
The paint() method looks like this:
4
...
}
Note that unlike the other major methods in this section, paint() takes an argument, an
instance of the class Graphics. This object is created and passed to paint by the browser, so
you will have to make sure that the Graphics class (part of the java.awt package) gets
imported into your applet code, usually through an import statement at the top of your Java
file:
import java.awt.Graphics;
A Simple Applet
1: import java.awt.Graphics;
2: import java.awt.Font;
3: import java.awt.Color;
4:
5: public class HelloAgainApplet extends java.applet.Applet {
6:
7: Font f = new Font(“TimesRoman”,Font.BOLD,36);
8:
9: public void paint(Graphics g) {
10: g.setFont(f);
11: g.setColor(Color.red);
12: g.drawString(“Hello again!”, 5, 50);
13: }
14: }
This applet overrides paint() method. The paint method is where the real work of this applet
(what little work goes on) really occurs. The Graphics object passed into the paint() method
holds that graphics state—that is, the current features of the drawing surface. Lines 10 and 11
set up the default font and color for this graphics state. Line 12 then draws the string “Hello
Again!” by using the current font and color at the position 5, 50. Note that the 0 point for y is
at the top left of the applet’s drawing surface, with positive y moving downward, so 50 is
actually at the bottom of the applet. Figure below shows how the applet’s bounding box and
the string are drawn on the page.
5
After you create a class or classes that contain your applet and compile them into class files
as you would any other Java program, you have to create a Web page that will hold that
applet by using the HTML language. 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.
To include an applet on a Web page, use the <APPLET> tag. <APPLET> is a special
extension to HTML for including applets in Web pages.
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment ]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
CODEBASE: CODEBASE is an optional attribute that specifies the base URL of the applet
code, which is the directory that will be searched for the applet’s executable class file
(specified by the CODE tag).
CODE: CODE is a required attribute that gives the name of the file containing your applet’s
compiled .class file.
ALT: The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser recognizes the APPLET tag but can’t currently run Java applets.This
is distinct from the alternate HTML you provide for browsers that don’t support applets.
NAME: NAME is an optional attribute used to specify a name for the applet instance.
Applets must be named in order for other applets on the same page to find them by name and
communicate with them.
WIDTH and HEIGHT: WIDTH and HEIGHT are required attributes that give the size (in
pixels) of the applet display area.
ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet. This
attribute is treated the same as the HTML IMG tag with these possible values: LEFT,
RIGHT,
6
TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
VSPACE and HSPACE: These attributes are optional. VSPACE specifies the space, in
pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of
the applet. They’re treated the same as the IMG tag’s VSPACE and HSPACE attributes.
PARAM NAME and VALUE: The PARAM tag allows you to specify applet-specific
arguments. Applets access their attributes with the getParameter( ) method.
Other valid APPLET attributes include ARCHIVE, which lets you specify one or more
archive files, and OBJECT, which specifies a saved version of the applet. In general, an
APPLET tag should include only a CODE or an OBJECT attribute, but not both.
Listing below shows a very simple example of a Web page with an applet included in it.
1: <HTML>
2: <HEAD>
3: <TITLE>This page has an applet on it</TITLE>
4: </HEAD>
5: <BODY>
6: <P>My second Java applet says:
7: <BR>
8: <APPLET CODE=”HelloAgainApplet.class” WIDTH=200 HEIGHT=50>
9: There would be an applet here if your browser
10: supported Java.
11: </APPLET>
12: </BODY>
13: </HTML>
The CODE attribute indicates the name of the class file that loads this applet,
including the .class extension. In this case, the class file must be in the same directory
as this HTML file. To indicate applets are in a different directory, use CODEBASE.
WIDTH and HEIGHT are required and used to indicate the bounding box of the
applet—that is, how big a box to draw for the applet on the Web page.
The text between the <APPLET> and </APPLET> tags is displayed by browsers that
do not understand the <APPLET> tag (which includes most browsers that are not Java
capable).
Advantages of applets
7
Safe! Because of the security built into the core Java language and the applet
structure, you don’t have to worry about malitious code causing damage to
someone’s system
Can be launched as a standalone web application independent of the host web
server
Disadvantages of applets
Applets can’t run any local executable programs
Applets can’t with any host other than the originating server
Applets can’t read/write to local computer’s file system
Applets can’t find any information about the local computer
All java-created pop-up windows carry a warning message
Stability depends on stability of the client’s web server
Performance directly depend on client’s machine
The Applet class also provides two methods that will help with the base URL
argument to getImage():
8
at http://www.myserver.com/htmlfiles/javahtml/, getDocumentBase()
returns a URL pointing to that path.
The getCodeBase() method returns a string representing the directory in
which this applet is contained-which may or may not be the same directory
as the HTML file, depending on whether the CODEBASE attribute
in <APPLET> is set or not.
Image img = getImage(
new URL("http://www.server.com/files/image.gif"));
In this similar form, the file image.gif is in the same directory as the applet itself:
Image img = getImage(getCodeBase(), "image.gif")
If you have lots of image files, it's common to put them into their own
subdirectory. This form of getImage() looks for the file image.gif in the
directory images, which, in turn, is in the same directory as the Java applet:
Image img = getImage(getCodeBase(), "images/image.gif")
The applet’s paint method displays the images. Graphics method drawImage() can be used to
display an image. Method drawImage receives four arguments. The first argument is a
reference to the Image object to display (logo1). The second and third arguments are the x-
and y-coordinates at which to display the image on the applet; the coordinates indicate the
upper-left corner of the image. The last argument is a reference to an ImageObserver object.
Normally, the ImageObserver is the object on which the program displays the image.
Java provides several mechanisms for playing sounds in an applet. The two simplest are
the Applet's play method and the play method of the AudioClip interface. Additional audio
capabilities are available in the Java Media Framework and Java Sound APIs. If you would
like to play a sound once in a program, the Applet method play loads the sound and plays it
once—the sound is marked for garbage collection after it plays. The Applet method play has
two versions:
9
The first version loads the audio clip stored in file soundFileName from location and plays
the sound. The first argument is normally a call to the
applet's getDocumentBase or getCodeBase method. Method getDocumentBase returns the
location of the HTML file that loaded the applet. (If the applet is in a package, the method
returns the location of the package or the JAR file containing the package.)
Method getCodeBase indicates the location of the applet's .class file. The second version of
method play takes a URL that contains the location and the file name of the audio clip. The
statement
play( getDocumentBase(), "hi.au" );
The sound engine that plays the audio clips supports several audio file formats,
including Sun Audio file format (.auextension), Windows Wave file
format (.wav extension), Macintosh AIFF file format (.aif
or .aiff extensions) and Musical Instrument Digital Interface (MIDI) file format (.mid or
.rmi extensions). The Java Media Framework (JMF) and Java Sound APIs support additional
formats.
Interface AppletContext
An applet runs inside a browser or applet viewer.
An applet running within a browser can ask the browser to do things for it:
10
Method Description
void showStatus(String Shows the message in the status line
message)
of the browser
Enumeration getApplets() Returns an enumeration of all the
applets in the same context (same web
page)
Applet getApplet(String Returns the applet in the current
name)
context with the specified name (null if
none exists)
void showDocument(URL Shows a new web page in the browser,
url)
displacing the current page.
void showDocument(URL Shows a new web page in the browser,
url, String target)
specifying the target frame
("_self", "_parent", "_top", "_blank", or
<frame-name>)
Image getImage(URL url) Returns an image object that
encapsulates the image specified by
the URL
AudioClip Returns an AudioClip object that
getAudioClip(URL url)
encapsulates the sound file specified by
the URL.
11
Let us see how to create a .jar file and related commands which help us to work with .jar files
1. Create a JAR file: To create a .jar file , we can use jar cf command in the following
way:
jar cf jarfilename inputfiles
Here, cf represents create the file. For example , assuming our package ‘pack’ is
available in C:\directory , to convert it into a jar file into the pack.jar , we can give the
command as:
C:\> jar cf pack.jar pack
Now, pack.jar file is created
2. Viewing a JAR file: To view the contents of .jar files, we can use the command as:
jar tf jarfilename
Here, tf represents table view of file contents. For example, to view the contents of
our pack.jar file, we can give the command:
C:/> jar tf pack.jar
Now , the contents of pack.jar are displayed as:
META-INF/
META-INF/MANIFEST.MF
pack/
pack/class1.class
pack/class2.class
..
..
where class1 , class2 etc. are the classes in the package ‘pack’. The first two entries
represent that there is a manifest file created and added to pack.jar. The third entry
represents the sub-directory with the name pack and the last two represent the files
name in the directory pack.
When we create .jar files , it automatically receives the default manifest file. There
can be only one manifest file in an archive, and it always has the pathname.
META-INF/MANIFEST.MF
This manifest file is useful to specify the information about other files which are
packaged.
3. Extracting a JAR file: To extract the files from a .jar file , we can use:
jar xf jarfilename
Here, xf represents extract files from the jar files. For example, to extract the contents
of our pack.jar file, we can write:
C:\> jar xf pack.jar
12
META-INF
pack // in this directory , we can see class1.class and class2.class.
4. Updating a JAR File: The Jar tool provides a ‘u’ option which you can use to update
the contents of an existing JAR file by modifying its manifest or by adding files. The
basic command for adding files has this format:
jar uf jar-file input-file(s)
here uf represent update jar file. For example, to update the contents of our pack.jar file,
we can write:
C:\>jar uf pack.jar
5. Running a JAR file: In order to run an application packaged as a JAR file, following
command can be used:
13