Chap11 Applets Final
Chap11 Applets Final
Chapter Index
Objectives
Introduction
Objectives
Understanding the meaning and significance of Applets.
To understand how to run applets in a web page.
Being able to create html document.
Using inbuilt java.awt and java.applet packages.
Creation of dynamic applets using parameter passing.
11.1 Introduction
Java provides another way of creating a special kind of GUI based programs that are embedded in a web
document called applets. The applets can run inside a web browser or by using utility appletviewer for
testing purpose. The applets can also be transported over the internet along with the web document using
the HTTP protocol. Different arguments can be sent to applets at run time make it dynamic and flexible
in nature.
1. Applets are executed as a part of a web page and its output is displayed within a Java-enabled
browser, whereas applications, are any general-purpose Java programs that donot need a Java
enabled web browser to execute.
2. Applets are designed mainly for handling the client side problems while the Java applications are
designed to work with the client as well as the server.
3. Applets usually don't have the main( ) method, whereas an application must have a main( ) method.
4. An applicationcan be CUI (Character User Interface) or GUI (Graphical User Interface), whereas
applet must run within a graphical user interface environment.
5. Applets have a limited access to the resources of the local machine, where the applets run. The
applications have full access to machine resources such as files or databases.
import java.applet.* ;
{
}
Output
Once the applet program is designed and ready to run, the following steps are required to build the
compile code:
Savesource file as MyApplet.java. The name of Java source file must be same as the applet class.
Compile the Java source file to create a class file.
Initialization State
In this phase, the applet is first initialized with values that are used by the applet later on.. The method
init( ) is overridden in the class for this purpose. This method is called by the web browser when an
applet is loaded first time or reloaded. It serves the same purpose as the constructor in the console based
program.
RunningState
The start phase occurs after the initialization phase when the web browser starts running the applet or
when the applet restarts again. The method start( ) is overridden in the class for this purpose and is
called automatically by the web browser every time the web page containing the applet is revisited.
Stop State
The applet enters in this phase, when it is no longer visible on the screen such as when the user moves to
a different Web page. The stop( ) method used for this purpose, is automatically called by web browser
to tell the applet that it should stop its execution. It is called automatically by java when the web page
that contains current applet is replaced by another page.
DisplayState
The paint phase occurs whenever the applet's output is drawn on the screen for the first time as well as
whenever the applet's output must be restored or changed. For this purpose, the paint( ) method is used
and is called once after start( ) method is called and again each time the web browser is activated.
Whenever the applet needs to redraw its output, the paint( ) methodis called. The paint( ) method takes
one parameter of type Graphics. This parameter contains the graphics context, which provides the
graphical environment in which the applet is running. This context is used to draw output to the applet
window. The Graphicsclasscontains several methods which can be used to draw string, line, oval,
rectangle etc. Inside paint( ) method, the drawString( ) method is used that outputs a string starting at
the specified X,Y location. Its syntax is:
void drawString(String msg, int x, int y)
Here, msgis the string to be output beginning at position x,y. In a Java window, the upperleft corner is at
location (0,0).
DeadState
This phase occurs when an applet ends and the system is ready to deallocate memory, i.e. to remove the
applet from memory. Like the initialization phase, the destroy cycle occurs only once. If your applet has
captured resources that need to be cleaned up before the applet exits, this is the place to do it. The
destroy( ) method is called by the browser only once, when an applet shuts down.
The following example demonstrates the use of some of the applet life cycle methods:
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
String msg = "" ;
public void init( )
{
msg += "Init method." ;
}
public void start( )
{
msg += “\nStart method" ;
}
public void paint(Graphics g)
{
msg += "\nPaint method" ;
g.drawString(msg,40,20);
}
}
Output
Comment Section
The comment section used to insert comments in the html code to make the program more user friendly.
The comments are not executed by the browser and are not displayed in the browser. The <!--...--> tag is
used to insert single or multiple line comments in the code. For example
<!--
This is multiple lines
Comments used in the code
//-->
Head Section
The head section contains the information about the HTML document like title, styles, links, scripts, and
other meta information.
The <title> tag is used to define the title of the document.
The <style> tag is used to declare style information for an HTML document.
The <base> tag specifies the base URL of another document.
The <link> tag defines a link to external style sheets
The <meta> tag provides information about the HTML document. The contents of <meta> tag will
not be displayed on the page.
The <script> tag declares a clientside scripting languages such as a JavaScript or VBScript.
An example of using head section and its tags is given below:
<html>
<head>
<title>Title of the document</title>
<style>
h1 {color:blue;}
p {color:red;}
</style>
<base href="http://www.gndu.ac.in/" target="Home Page">
<link rel="stylesheet" type="text/css" href="sheet.css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript">
</head>
</html>
Body Section
The body section contains all the contents of the html document, such as texts, hyperlinks, images, lists,
tables, forms etc.
<html>
<body>
Contents of document
</body>
<html>
Applet Tag
The applet tag is used to embed an applet in a web page and provides the necessary information about
the location of the applets’s class file. The applet will be loaded and executed by a Javaenabled web
browser when it encounters the applet tag within the HTML file. The syntax is:
<APPLET code = “appletName.class”width=value height =value>
</APPLET>
Some of the attributes of Applet tag of HTML are:
code It specifies the name of the .class file. If the .class file is in some other folder
than .html file, its path has to be mentioned.
width The width of an applet in pixels is specified using integer value.
height The height of an applet in pixels is specified using integer value.
When a Java-enabled browser encounters an <APPLET> tag, it performs the following operations:
Reserves a display area of the specified width and height for the applet.
Loads the bytecode for the specified applet class.
Creates an instance of anapplet.
Calls the applet’s methods such as init( ), start( ) methods etc.
<HTML>
<Head>
<Title>
A Simple Applet
</Title>
</Head>
<Body>
<Applet code="MyApplet.class" width="150" height="50">
</Applet>
</Body>
</HTML
In the above HTML code, the class file “MyApplet.class” is embedded using the applet tag. For
simplicity, the HTML file and applet class file should be saved in the same folder.
Types of Applets
In Java, applets are of two types: Signed and Unsigned. The unsigned applets are considered to be un-
trusted and operate within a security sandbox that allows only a set of safe operations. The unsigned
applet can only communicate with the server from which it was downloaded and cannot access the
resources of the local machine on which it is running.
On most browsers, unsigned applets cannot perform the following tasks:
Applets cannot access client resources such as the local file system and executable files
Applets cannot communicate with any server other than the server from which they were
downloaded.
Applets cannot load native libraries.
Applets cannot initiate a printing job.
On the other hand, the signed applets require a digital certificate to indicate that they come from trusted
site. Hence, they operate outside the security sandbox and have extensive capabilities to access the client
side resources.
The applet can be executed like an application by adding a main( ) method to the applet. There is no
need to create a new class. It may seem a little strange that adding a main( ) method to a class will make
it into an application, but that's the most common way of doing it. An application is any program that
has a main( ) method. To run an applet as an application, the following steps are required:
1. Include main( ) method in an applet that will execute when you run applet as an application.
2. Create a Frame window that is used to hold the applet.
3. Create a new instance of an applet and insert it to the parent window.
4. Start the applet by calling init( ) from the main( ) method and then start( ) if these methods are
overridden in applet.
5. Finalize the layout.
6. Make the frame window visible.
import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet
{
String msg = "Hello Everybody..." ;
Output
A Java applet has the capability of receiving the argument values passed from the html page using
parameter attribute of the applet tag as illustrated below:
The parameter names used and their corresponding values are by default strings, whether or not they are
quoted. Therefore an applet check that a valid string is returned as a parameter value. For each
parameter the NAME attribute must be specified, but the VALUE attribute is optional. The applet
should use a default value if no valid string is returned.The Applet class of the package java.awt.applet
contains a getParameter( ) method used to retrieve a value of the specified parameter as a String
object:
public String getParameter(String name)
It returns the value of the named parameter in the HTML tag. The name argument is case
insensitive.The parameter passing mechanism can be illustrated with the help of an example:
import java.applet.*;
import java.awt.*;
public class parameterApplet extends Applet
{
String arg = "Welcom to Java Applet." ;
public void paint(Graphics g)
{
String msg = getParameter("Message");
if (msg == null)
msg = arg ;
g.drawString(msg, 50, 25);
}
}
<HTML>
<HEAD>
<TITLE>Parameter Passing to Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="parameterApplet.class" width="350" height="200">
<PARAM name="Message" value="Welcome to Web Pages using Java Applets.">
</APPLET>
</BODY>
</HTML>
Output
Check Your Progress / Self Assessment Questions
Ques 9. Which utility is used to run an applet without embedding it in html document?
Ques 10. Which method is used to receive argument values from html document?
Summary
Java offers GUI based special programs called applets that are executed in a java enabled web browser
and can transport over the internet using Http protocol alongwith web document. The Applet class
contained in java .applet package is used to create an applet. The Applet class contains several methods
that are used to control the execution of an applet. An applet is a part of web documents and can be
inserted in an html page using <applet > tag. To run an applet, open the web page containingthe applet
in any Java enabled web browser or use the utility appletviewer. To create an applet, the following
inbuilt packages are used:
• java.awt : provides GUI environment
• java.applet: provides classes to create an applet
Applets are of two types: signed and unsigned. The unsigned applets are executed in a restricted
environment and cannot access the resources of the client machine, whereas, the signed applets can
access the resources. To make the applet dynamic in nature, an applet and html document can
communicate with others through the passing of parameters.
Glossary
Applet : a GUI based programs that runs in a web browser.
Application : a java program that does not need browser to run.
Life cycle : stages in the life of an applet.
Init: First stage in the life of an applet.
start( ) : start method is overridden used in java class, it provides what an applet will do.
Java.awt: abtract window toolkit package of java that provides window environment to an
application.
HTML : Hyper Text Markup Language, a language used to design web pages. Its commands are
called tags.
java.applet : Another builit in package of java that provides Applet class to create an applet.
<applet> tag : html tag used to insert an applet in html document.
Param : HTML tag, used to provide parameters to an applet.
appletviewer: Java built in utility to run and test an applet, without using browser.
Model Questions
1. What is the difference between an application and an applet?
2. How can an applet be embedded in a web document.
3. Explain life cycle of an applet.
4. What is the use of <head> and <body>sections in HTML?
5. What is use of Applet tag in HTML ?
6. How can arguments be sent to an applet ?
7. What is the difference between signed and unsigned applets?
8. What are various advantages of applets in java?