CHAPTER 10
APPLETS
10.1 INTRODUCTION
In Java technology, applets are applications that can be accessed on a internet
server, transfer over internet, download from the internet and run as web
document. Java applets run on the Java enables web browsers such as mozila and
internet explorer. An applet must be a subclass of the java.applet.Applet class.
Like any application, an applet can perform arithmetic operations, display picture,
graphics, play sound, accept input form user, play games, create animation etc.
The Applet class provides the standard interface between the applet and the
browser environment.
There is another package called, Swing provides a special subclass of the Applet
class called javax.swing.JApplet. The JApplet class should be used for all applets
that use Swing components to construct their graphical user interfaces (GUIs).
Applets are programs that require a browser to run. Applets are typically
downloaded from the Internet and run in an applet window within a browser.
Because applet is not structured in, the same way as the application program.
Therefore, you will find applets differ from application programs in several key
areas. Applets impose certain limitations and restrictions in their design.
a. Applet do not use the main() method for initiating the execution of the
code.
b. Applet cannot be run independently. As above describe, they run inside a
web page using a special feature known as applet tag inside the HTML
tag.
c. Applets get their parameters not from the command line but from the web
page within which they run.
10.2 APPLET SECURITY RESTRICTIONS
In Java, technology when we dealing with web application, an Applet loaded over
the network are generally considered being un-trusted code. An un-trusted applet
cannot perform any actions such as deleting your files, sending out fake email that
looks like it came from you, using your computer as a remote file server. For this
reason, Web browsers and applet viewers carefully restrict what an applet is
allowed to do. When designing an applet application, we must be aware of a long
list of things that an applet is not allowed to do. The following list details the
security restrictions imposed by the appletviewer application in Java. In general,
way we should assume that your applets would be restricted in the following
ways:
1. In applet application, the un-trusted code cannot read from or write to the
local file system. This means that un-trusted code cannot do the following
things :
a. Can not read any type of files, write any type files and delete any type
files
b. Cannot rename files or check for the existence of files
c. It cannot read or write from FileDescriptor objects.
d. Cannot obtain the list of directories or create directories.
e. Cannot get the size or modification date of files.
f. It cannot get the read and write permissions of a file.
g. It cannot test whether a filename is a file or directory.
2. Appletviewer allows a system administrator to set properties that allow
applets to read and write files within a specified list of directories. An un-
trusted code cannot perform networking operations, except in certain
restricted ways. An un-trusted code cannot do following things:
a. Cannot create a network connection to any computer other than the
one from which the code was itself loaded.
b. Cannot accept network connections on ports less than or equal to 1024
or from any host other than the one from which the code itself was
loaded.
c. Cannot use multicast sockets.
3. The un-trusted code cannot make use of certain system facilities, such as:
a. It cannot exit the Java interpreter by calling System.exit() or
Runtime.exit().
b. It cannot Spawn new processes by calling any of the Runtime.exec()
methods.
c. Dynamically load native code libraries with the load() or loadLibrary()
methods of Runtime or System.
4. The un-trusted code cannot make use of certain AWT facilities, such as :
a. It cannot initiate a print job.
b. It cannot access the system clipboard.
c. It cannot access the system event queue.
5. The un-trusted code cannot access to system properties. It cannot call
System.getProperties(), and so cannot modify or insert properties into the
system properties list. It can call System.getProperty() to read individual
properties, but can only read system properties to which it has been explicitly
granted access.
6. The un-trusted code has restrictions on its use of the java.security package
such as :
a. Cannot manipulate security identities in any way.
b. Cannot set or read security properties.
c. It cannot list, lookup, insert, or remove security providers.
7. The class loader ensures that all un-trusted Java code is passed through the
Java byte-code verification process. It also checks that the code:
1. Is valid Java Virtual Machine code.
2. Does not overflow or underflow the stack.
3. Does not use registers incorrectly.
4. Does not convert data types illegally.
10.3 THE CLASS HIERARCHY FOR APPLETS
In Java, class hierarchy that Applet is itself a subclass of the Panel class, which is
further derived from a class called Container, and so on, as shown in Fig.10.1.
Component is a subclass of Object, so all of these classes are a kind of Object.
The Object class is at the top of the Java class hierarchy; Object does not have a
superclass. Every other class in the Java API inherits behavior from Object, which
defines a few basic methods.
Fig. 10.1 Part of the Java Class Hierarchy
In this sense, an Applet is a kind of Panel, which itself a kind of Container and
each of these can ultimately be considered a kind of component.
We can correctly refer to HelloWeb as an Applet because subclassing can be
thought of as creating an "is a" relationship, in which the subclass is a kind of its
superclass. HelloWeb is therefore a kind of Applet.
10.4 LIFE CYCLE OF APPLET
In this section, we learn about the lifecycle of an applet and different methods of
an applet. Applet runs in the browser and its lifecycle method are called by JVM
when it is loaded and destroyed. As a result, when an applet is load, it changes its
states as shown in Fig. 10.2. The applet states include:
a. Born or initialization state using init() method
b. Running state using start() method
c. Paint state using paint() method
d. Stop state using stop() method
e. Dead or destroy state using destroy() method
Load
Applet
Born
state
start()
Display stop()
paint()
start()
destroy()
End
Exit from the Browser
Running Stop
state state
Destroy
state
Fig. 10.2. The Life Cycle of applet
1. Born or initialization state. The init() method is called to initialized
an applet. The life cycle of an applet is begin on that time when the applet
is first loaded into the browser and called the init() method. The init()
method is called only one time in the life cycle on an applet. The init ()
method is used for initialization of variables and the objects like image,
sound file are loaded in the init () method. We can tap into the
initialization stage by overriding the Applet class init() method as
following:
public void init()
{
------------------
------------------ body of init() method
}
2. Running State. An applet enters in running state when the system calls
the start() method and when the browser is ready to run the applet. The
start method of an applet is called after the initialization method init(). The
start() method may be called multiples time of the life cycle of an applet
when the applet needs to be started or restarted. For Example if the user
wants to return to the Applet, in this situation the start method () of an
applet will be called by the web browser and the user will be back on the
applet.
In the words by using start() method user can interact within the applet. To
provide your own start code, override the applet class start() method as
following.:
public void start()
{
------------------
------------------ body of start()method
}
3. Paint state or Display state. The paint state or display state occurs
whenever the applets display must be drawn on the screen. This happens
right after the applet start stage, as well as whenever the applet display
must be restored or changed. Almost in every applet you will have to write
a paint() method, to provide your own paint code, override the Applet
class paint() method as following:
public void paint( Graphics ob)
{
------------------
------------------ body of paint()method
}
4. Stop state. The stop state can be occurs multiple times in the life cycle
of an Applet. Stopping occurs automatically when we leave the page
containing the currently running applet. For this purpose, The stop()
method can be called multiple times in the life cycle of applet like the start
() method. Or should be called at least one time. There is only miner
difference between the start() method and stop () method. For example the
stop() method is called by the web browser on that time, when the user
leaves one applet to go another applet and the start() method is called on
that time when the user wants to go back into the first program or applet.
The stop() can be overriding is as following:
public void stop()
{
------------------
------------------ body of stop()method
}
5. Dead or destroy state. An applet is said to be dead when it is
removed from the memory by using destroy() method. The destroy()
method is called only one time in the life cycle of applet like init()
method. This method is called only on that time when the browser needs
to close. The destroy() can be overriding is as following:
public void destroy()
{
------------------
------------------ Body of destroy() method
}
10.5 CREATING AN EXECUTABLE APPLET
Before creating any applet in Java, we must insure that the appletviewer tool
is available or not, because appletviewer can run and debug applets without a
web browser other wise a Java enable browser is available to run the applet.
We make sure that java is properly installed. The steps to developing and
executing an applet are as following:
Step 1. Write the source code to create a java source file(.java file) for
example MyApp Applet as shown in program 10.1.
Program 10.1 Source File of An applet
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
public void paint(Graphics g)
{
g.drawString("This is MY First Applet ",50,100) ;
}
}
Step 2. Compile the source file using javac (it creates a .class file).
Step 3. Create a minimal html file using <applet> as shown in example
program 10.2 and save it as MyApp.html
Program 10.2 An Minimum Html Code For MyApp
<applet code = “MyApp.class” height = 400 width = 300>
</applet>
Step 4. To view the applet in appletviewer: Run the appletviewer tool in
following ways:
The applet viewer tool displays an applet window and displays the output “This is
MY First Applet” in this window as following.
In above program, the first line in the MyApp program is import java.awt.*; and
the second line import java.applet.*. The import statement is an instruction to the
compiler to help resolve class names. An import statement helps to refer to the
classes in the java.awt package by their short names. Thus to refer to the Graphics
class, we now use the statement.
public void paint (Graphics g)
Without the import statement, we would have to use the fully qualified name:
public void paint ( java.awt.Graphics g)
The MyApp does not use the init(), start(), stop(), or destroy() methods. It uses
only the paint method. The paint method takes a Graphics object as an argument.
The Graphics class is part of the Abstract Windows Toolkit (awt) package.
The declaration public void paint (Graphics g) says that the Graphics object will
be referred by the name g within the paint method. “g” is only an identifier, and
can be replaced by any other identifier, such as “p”. e the graphics class works in
the graphics mode (as in classic C), the preferred method is to draws strings rather
than perform console output. The statement
g.drawString (“Hello World Applet!”, 50, 100);
This means that the string is to be drawn at pixels x=50, y=100, relative to the
applet window, measured from the top left hand corner of the applet window. As
observed before, an applet cannot run on itsown, and must run within a browser.
Hence the applet code must be supplemented with HTML code. The minimum
HTML code that is needed for appletviewer is the following.
<applet code = “MyApp.class”height = 300 width = 400>
</applet>
If the applet class file is not in the same directory as the web page, then use the
syntax CODEBASE= URL with the URL or path of the directory where the
applet class file is located.
10.6 Designing a Web Page
To run the above applet on a web browser we will use the following step:
Step 1: Preparing to view the applet in a browser: Wrap the above applet tag
within any desired html code as shown in program 10.3 and save the file with
name MyApplet2.html.
Program 10.2 an Html Code for MyApplet2
<HTML>
<HEAD>
<TITLE>Hello Wel Come to My web</TITLE>
</HEAD>
<BODY>
This is what my applet does in a web browser :
<applet code = "MyApp.class" height = 400 width = 300>
</applet>
</BODY>
</HTML>
Step 2: Open the above html file using any java-enabled browser such as use
“Open Internet Explorer ->File-> Open page->Browse-> MyApplet2.html->OK”
on internet explorer or Netscape Navigator the applet will automatically run in the
assigned area as shown in the below output.
10.7 THE PARAM TAG (Passing Parameter to
applets)
Unlike applications program, which take command line parameters, applets get,
their parameters using the <PARAM> tag in the HTML code. Passing parameter
to an applet code using the <PARAM> tag is similar to passing parameters to the
main() method using command line arguments. This is done by using the
getParameter method in the applet code. The <PARAM> tag has the syntax:
<PARAM NAME="parameter-name" VALUE="parameter-value">
Each <PARAM > tag has a name attribute such as color, and a value attribute
such as red. Inside the applet code, the applet can refer to that parameter by name
to find its value. For example, if we want to change the color of the text display to
blue by an applet by using <PARAM> tag. This is done as following:
<APPLET ----------------->
<PARAM NAME = color VALUE= “blue”>
In the same way, if we want supply new text to an applet throw the <PARAM>
tag. This is done by as following:
<APPLET NAME =MyText VALUE=”This is the Magic of Java”>
The getParameter method has the prototype:
String getParameter (String parameter_name)
In the program, 10.3 shows how two parameters are obtained by the apple code in
file ParamDemo.java.
Program 10.3 Getting parameter throws the PARAM tag
import java.awt.*;
import java.applet.Applet;
public class ParamDemo extends Applet
{
String s1, s2;
public void init()
{
s1 = getParameter ("Name");
s2 = getParameter ("Class");
}
public void paint(Graphics g)
{
if (s1 != null)
g.drawString (s1, 50, 100);
else
g.drawString ("No Name", 50, 100);
if (s2 != null)
g.drawString (s2, 50, 200);
else
g.drawString ("No Class", 50, 200);
}
}
After compiling the above program (ex. javac ParamDemo.java), create an HTML
file MyParam.html as shown in the program 10.4.
Program 10.4
<applet code = ParamDemo.class height = 100 width = 100>
<param name = Name value = "Pawan Thakur">
<param name = Class value = "M.Tech Computer Science">
</applet>
Now save the file as ParamDemo.html and then run the applet using the applet
viewer as following:
Appletviewer ParamDemo.html
Output:
10.8 An Applet Skeleton
The MyApp applet used only the paint method. The ParamDemo applet used
only the init and the paint methods. Most applets overridden a set of methods that
provide the basic mechanism by which the applet viewer interfaces to the applet
and control its execution. Four of these methods- init(), start(),stop(), and
destroy() are define by Applet. To see how they are called, we can use the
following applet code as shown in program 10.5. The code also shows how
applets may use the console, although they usually do not for obvious reasons.
Program 10.5 An Applet Skeleton
import java.awt.*;
import java.applet.Applet;
public class TestApplet extends Applet
{
static int countInit=0;
static int countStart=0;
static int countStop=0;
static int countPaint=0;
static int countDestroy=0;
public void init()
{
System.out.println ("Init Method = " + (++countInit));
}
public void start()
{
System.out.println ("Start Method = " + (++countStart));
repaint();
}
public void stop()
{
System.out.println ("Stop Method= " + (++countStop));
repaint();
}
public void paint (Graphics g)
{
System.out.println ("Paint Method= " + (++countPaint));
/*repaint();//recursive call to paint*/
}
public void destroy()
{
System.out.println ("Destroy Method=" + (++countDestroy));
repaint();
}
}
After compiling the above program (ex. Javac TestApplet.java), create an HTML
file TestApplet.html as shown in the program 10.6.
<applet code="TestApplet.class" width=300 height =500>
</applet>
Now save the file as TestApplet.html and then run the applet using the applet
viewer as following:
Appletviewer Test.html
Although this skeleton does not do anything and will generate the following
output in console window:
Output:
10.9