Java Applets
Introduction
• Java supports two types of programming :
1) Application program:
Application is a program that runs on your computer under the operating system of that
Computer.
2) Applet program:
An applet is an application designed to be transmitted over the Internet and executed
by a Java-compatible Web browser.
Compare Web Applet and Stand-alone application
Or
Applet program and application program
Applet Application Program
NO
(web applet) (Stand-alone application)
An applet is an application designed to Application is a program that runs on
be transmitted over the Internet and your computer under the operating
1
executed by a Java-compatible Web system of that Computer.
browser.
Applet is dynamic program which is run Application is static program which
2
on browser. run using java interpreter.
Applet do not use the main () method Application uses main () method for
3
for initiating the execution of the code. execution of the code.
Applets cannot be run independently. Application runs independently using
They must be run under an applet javac compiler.
4
viewer or a java compatible web
browser.
Applets cannot read or write files on the Application can read write files on
5
web user’s disk. the web user’s disk.
Applet cannot communicate with other Application can communicate with
6
server on the network. other servers on the network.
Applet cannot run any program from the Application program can run from
7
local computer. local computer.
Application program can use
Applets are restricted from using
methods of c, c++ libraries.
8 libraries from other languages such as
c, c++.
Applet concept
Applet is small programs that are primarily used in internet computing, they can be
transported over the internet from one computer to another and run using applet viewer
or java compatible web browser.
Java applet is a java class that you embed in an HTML page and is downloaded
and executed by a web browser.
Applet can’t be executed directly.
For running an applet, HTML file must be created which tells the browser what to
load and how to run it.
applet begins execution via loading of a HTML page “containing it” after that java
enabled web browser or “applet viewer” is required to run an applet
Now, Web pages not only contain static text or simple image but it can also perform
arithmetic operation, displays graphics, play sounds and moving Images.
We can embed applets into web pages in two ways:
1. We can write our own applets and embed them into web pages.
2. We can download an applet from a remote computer system and then embed it into
a web page.
Types of applet:
1) Local Applet
An applet developed locally and stored in a local system is known as local applet.
When a web page is trying to find a local applet, it does not need to use the Internet
and therefore the local system does not require the Internet Connection.
It simply searches the directories in the local system and locates and loads the
specified applet.
User can write his own applets and embed them into web pages.
2) Remote Applet
An applet which is developed by someone else and stored on a remote computer
connected to the Internet is known as remote Applet.
If our system is connected to the Internet, we can download the remote applet onto our
system via Internet and then run it.
User can thus download an applet from a remote computer sys
In order to locate and load a remote applet, we must know the applet’s address on web.
This address is known as URL (Uniform Resource Locator) and must be specified in
the applet’s HTML document as the value of the CODEBASE attribute.
EX: CODEBASE= http: // www. [Link] /applets
In case of local applets, CODEBSAE may be absent or may specify a local directory.
Limitations of applet
All the restriction and limitations are placed in the interest of security of systems. These
ensure that an applet cannot do any damage to local system.
Applets allow neither to execute any application nor to load any DLL s on the local
system.
Applets do not need a main method.
Applet runs under an applet viewer or a java compatible web browser.
Applets can’t read or write files on the web user’s disk. If information must be saved to
disk as an applet is executing, the storage of information must be done on the disk from
which the web page is served.
Applet cannot make network connection to a computer other than the one from which
the web page is served, expect to direct the browser to a new location.
Applets are restricted from using libraries from other languages such as C,C++.
Applet cannot run any programs on the web user’s system, including browser plug-ins,
activeX controls or other browser related items.
Some of Java’s functionality (like removal of pointers, verification of byte code and
restricted remote and local file access) blocked for applets because of security
concerns.
When to use Applet?
When we need something dynamic to be included in the display of a web page.
When we require some flash outputs. For example, applets that produce sounds,
animations or some special effects would be used when displaying certain pages.
When we want to create a program and make it available on the internet for us by others
on their computers.
The Applet class
[Link] class is actually a subclass of [Link].
[Link] is smallest package in Java API.
It consists of a single class and three interfaces:
o Class : Applet class
o Three Interface: Applet Context, AppletStub and Audio clip.
Applet class contains only a single default parameter less constructor, which is not
used generally.
Applets are constructed by the run time environment when they are loaded, they do not
have to be explicitly constructed.
Applet class contains 21 methods that are used to display images, play audio files,
respond to events and obtain information about applet’s execution environment,
referred as applet’s context.
Applet class Hierarchy
Methods of Applet class
No Methods Action
1 Image getImage(URL url): Used to retrieve an Image identified by
URL
2 AudioClip getAudioClip(URL url) Used to retrieve Audioclip object that is
identified by URL.
Void play(URL url): If an audioThe play method is used to
3
play an audio clip
void init( ), void start() Used to implement each of four life
4
void stop(), void destroy( ) : cycles stages of an applet.
5 boolean isActive() : Return true if applet has been started
else return false if it has been stopped
AppletContext getAppletContext(): Used to obtain AppletContextObject
6
associated with an applet.
String getAppletInfo(): Returns a string object that provides
information about applet. this includes
7 version, copyright and ownership data
as well as applet specific data.
8 URL getCodeBase() : Returns base URL specifying the
applet’s location.
URL getDocumentBase(): returns the URL of the HTML document
9 in which the applet is contained
Used to obtain parameter data that is
String getParameter(String passed to an applet in an HTML
10
paramname): [Link] null if parameters not found.
11 String [ ] [ ] getParameterInfo() : Returns array that describe all the
parameters used by an object
Used to resize an applet according to the
12 void resize(Dimension dim):
dimensions specified by dim.
Used to display a status message in the
13 void showStatus(String str) : status window of the browser or
appletviewer.
Used to set the AppletStub associated
14 void setStub(AppletStub stubObj): with the applet. It should not be used
unless you are constructing your own
custom applet viewer.
Stub:
A stub is a small piece of code that provides the linkage between your applet and
the web browser.
AppletContext Interface
It defines methods that allow an applet to access the context in which it is being run.
AppletContext interface is accessed using getAppletContext() method of Applet class.
It provides 7 methods that allows an applet to obtain information about and manipulate
its environment.
1. Enumeration getApplets()
2. Applet getApplet(String name)
3. AudioClip getAudioClip(URL url)
4. Image getImage(URL url)
5. void showDocument(URL url)
6. void showDocument(URL url ,String str)
7. void showStatus(String str)
AudioClip interface
It defines three methods:
1. void play(URL url) :to play an audio clip
2. void stop(): to terminate the playing of an audio clip.
3. void loop(): to start and play an audio clip in a continuous loop.
Simple Applet display Method
No. Method Description
void drawString(String message, int x,int y) To output a string to an Applet.
1
e.g. drawString(“hi”,10,100)
void setBackground(Color colorname) To set the back ground of a applet
2 e.g. setBackground([Link]) window
void setForeground(Color colorname) To set the foreground color of an
3 e.g. setForeground([Link]) applet window.
Color getBackground() To obtain the current settings for the
4
background color.
Color getForeground() To obtain the current settings for the
5
foreground.
Applet getApplet(String name) To obtain the applet specified by
6 given name from the current applet
context.
void showStatus(String status) To display the status message in the
7
status bar of applet window.
URL getDocumentBase() To obtain the directory of the current
8
browsers page.
URL getCodeBase() To obtain the directory from which
9
the applet’s class file was loaded.
Color class:
we can fill colors in applet using Color class of awt package.
Pre-defined colour in java:
[Link] [Link] [Link] [Link]
[Link] [Link] [Link] [Link]
[Link]
[Link] [Link] [Link]
[Link]
For example this sets background color to green and text color to red:
setBackground([Link]); or
setForeground([Link]); or
setColor([Link]);
Color constructor:
We can create any new color bu using constructor of Color class.
It takes three integer parameters and uses RGB combination for creating
new colors.
Color colorobj=new Color (int red ,int green, int blue );
E.g: Color c=new Color(255,100,100);
[Link]( c );
Color Obtained Red Value Green Value Blue Value
White 255 255 255
Black 0 0 0
Lightgray 192 192 192
darkgray 128 128 128
Red 255 0 0
Green 0 255 0
Blue 0 0 255
Yellow 255 255 0
purple 255 0 255
Applet life cycle
• Every java applet inherits a set of default behaviours from the Applet [Link] when
an applet is loaded ,it undergoes a series of changes in its state.
• The applet states are:
1. Born or Initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
1) Initialization state
• Applet enters the initialization state when it is first [Link] is achieved by calling
the init() method of Applet [Link] applet is born.
• Initialization occurs only once in the applet’s life cycle.
• We do following at this stage,
- create objects needed by the applet
- set up initial values,initailize variables
- Load images or fonts
- set up colors
• To provide any of behaviour mentioned above,we must overrride init() method:
public void init()
{
. .......... (Action)
............
}
2) Running state
• Applet enters the running state when the system calls start() method of Applet
class.
• This occurs automatically after applet is initialized.
• Starting of applet can also occur if the applet is already in “stopped” (idle) state.
• Unlike init() method,the start() method may be called more than once.
• We may override the start() method to create a thread to control the applet.
public void start( )
{
. .......... (Action)
............
}
3) Idle or stopped state
• An applet becomes idle when it is stoppped from running.
• Stopping occurs automatically when we leave the page containing the currently
running applet.
• We can also stop applet by calling the stop() method explicitly.
• If we use thread to run the applet then we must use stop() method to terminate the
thread.
• To do this override stop() method:
public void stop()
{
. ................ (Action)
..................
}
4) Dead state
• An applet is said to be dead when it is removed from memory .this occurs
automatically by invoking the destroy() mehtod when we quit the browser.
• Destroying stage occurs only once in the applet’s life cycle.
• If the applet has created any resources,like threads we may override detstroy()
method to clean up these resources .
public void destroy()
{
...............
................
}
5) Display state
• Applets moves to the display state ,whenever it has to perform some output
operations on the screen.
• This happens immidiately after the applet enters into the running state.
• The paint() method is called to accomplish this task.
• Almost every applet will have paint() method .deault version of paint() method
does nothing.
• We must have to override paint() if we want anything to be displayed on the screen.
• Display state is not considered as a part of the applet’s life cycle.
• The paint() method is defined in the applet [Link] is inherited from the
Component class ,a super class of Applet.
public void paint()
{
. ........... (Display statements)
.............
}
Steps to developing and testing an applet:
1) Building an applet code(.java file)
2) Creating an executable applet (.class file)
3) Designing a web page using HTML tags
4) Preparing <APPLET> tag
5) Incorporating <APPLET> tag into the web page
6) Creating HTML file
7) Testing the applet code
1. Building an applet code
Applet code uses the services of two classes,namely Applet and Graphics from java
class.
Applet class is contained in [Link] package ,which provides life and behaviour
to the applet through its methods such as init() ,start() and paint().
Applet class maintains the life cycle of an applet.
When an applet is loaded ,java automatically calls a series of Applet class methods for
the starting,running,stopping the applet code.
When paint() method is called ,it will actually display the result of the applet code on
the [Link] output may be text,graphics or sound.
The paint() method requires a Graphics object as an argument.
public void paint (Graphics g)
We have to import [Link] package that contains Graphics class.
All output operation of an applet are performed using the methods defined in the
Graphics class.
The appletclassname is the main class for the [Link] the applet is loaded ,java
creates an instance of this class and then create Applet class methods are called on that
instance to execute the code.
appletclassname should be declared public because it is main applet class.
General format of applet code:
import [Link].*;
import [Link].*;
.........
.........
public class appletclassname extends Applet
{
............
............
public void paint(Graphics g)
{
//Applet operation code
}
............
............
}
//save file with name [Link] in a java subdirectory
import [Link];
import [Link];
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("Hello Applet",50,50);
}
}
2. Creating an executable applet
• Executable applet is .class file of the applet which is obtained by compiling the
source code of the applet.
• Compiling an applet is same as compiling an application.
Ex : [Link]
1) Move to directory containing the source code and type command:
javac [Link]
2) The compiled output file called [Link] is placed in same directory as the
source .
3) If any error message is received ,then we must check for errors ,correct themand
compile the applet again.
3. Designing webpage using HTML
Java programs resides on web [Link] run a java applet ,it is necessary to have a web
page that reference that applet.
A web page is made up of text and HTML tags that can be interpreted by a web
browser or appletviewer.
A web page is also known as HTML page or HTML document.
Web pages are stored using a file extension .html
HTML files should be stored in the same directory as the compiled code of the
applets.
Web page is divided in to three major sections:
1) Comment section(optional) 2) Head Section(optional) 3) Body section
Head section:
<HEAD>
<TITLE> Welcome to Java Applets </TITLE>
</HEAD>
Here,text enclosed in <TITLE> and </TITLe> will apper in the title bar of the web
browser when it displays the page.
Body Section:
After Head section comes the body [Link] section contains the entire information
about the web page and its behaviour.
<BODY>
<CENTER>
<H1> WELCOME </H1>
</CENTER>
<APPLET ....... >
</APPLET>
</BODY>
HTML tags
• <HTML> ...........</HTML>
• <HEAD>. ......... </HEAD>
• <TITLE>. ......... </TITLE>
• <BODY> .......... </BODY>
• <H1>........</H1>.......<H6>. ......... </H6>
• <CENTER>........... </CENTER>
• <APPLET. >
• <APPLET...> .......... </APPLET>
• <PARAM ... >
• <B>.......... </B>
• <BR>
• <P>
• <IMG.......... >
• <HR>
• <A .... ></A>
• <FONT>. ......... </FONT>
• <!....................> (comment line)
4. Preparaing Appplet tag
• <APPLET ....> tag supplies the name of applet to be loaded and tells the browser
how much space the applet requires.
• The ellipsis in the tag <APPLET .... > indicates that it contains certain attributes that
must be specified.
• Minimum requirement of <APPLET> TAG:
<APPLET CODE= [Link] WIDTH=200 HEIGHT=400 >
</APPLET>
This HMTL code tells the browser to load the compiled java applet
[Link] ,which is in the same directory as this HTML file .and also specify display
area for the applet output.
5. Adding applet to HTML file
<html>
<applet code="[Link]" width="300" height="200"></applet>
</html>
6. Running an applet
We must have following files in our current directory:
1) [Link]
2) [Link]
3) [Link]
• To run an applet ,we require one of following tools:
1) Java enabled web browser :if we use it,we will be able to see the entire web page
containing the applet.
2) Java appletviewer:
• if we use it,we will only see the applet output.
• appletviewer is not full fleged web browser and therfore it ignores all of the HTML
tags except the part which runs applet.
Syntax:
appletviewer [Link]
Appplet tag
• <APPLET ....> tag supplies the name of applet to be loaded and tells the browser
how much space the applet requires.
• The ellipsis in the tag <APPLET..... > indicates that it contains certain attributes that
must be specified.
• Minimum requirement of <APPLET> TAG:
<applet code="[Link]" width="300" height="200">
</APPLET>
This HMTL code tells the browser to load the compiled java applet
[Link] ,which is in the same directory as this HTML file .and also specify display
area for the applet output.
Attributes of Applet tag
< APPLET
[CODEBASE= codebase_URL]
CODE=[Link]
[ALT = Alternate_text ]
[Name = applet_instance_name ]
WIDTH = Pixels
HEIGHT = Pixels
[ ALIGN= Alignment]
[ VSPACE = Pixels ]
[ HSPACE = Pixles]
>
[ <PARAM NAME=name1 VALUE= value1 >]
[ <PARAM NAME=name2 VALUE= value2 >]
..............
</APPLET>
Everything in [ ] indicates the option can be used when integrating an applet into a
webpage.
Attributes of Applet tag:
NO Attribute Meaning
Specifies the name of the applet class to be
loaded.
1 CODE=[Link] It is the name of already compiled .class file in
(necessary) which the executable java byte code for the applet is
stored.
CODEBASE= codebase_URL Specifies URL of the directory in which the applet
2 (Optional) resides.(must used in remote applet)
Specify width and height of the space on the
3 WIDTH = Pixels
HTML page that will be reserved for applet.
HEIGHT = Pixels(necessary)
A name for the other applet on the page may refer
Name = applet_instance_name
4 to this applet. This facilitates inter applet
(Optional)
communication.
Alignment of applet on page:
[ ALIGN= Alignment] Values for alignment are:
5
(Optional)
(TOP, BOTTOM, LEFT, RIGHT,
MIDDLE,ABSMIDDLE,ABSBOTTOM,
TEXTTOP,BASELINE )
[ VSPACE = Pixels ] It specifies amount of vertical blank space the
(Optional) browser should leave surrounding the applet.
6
it is Used only when ALIGN some vertical
alignment is specified with the ALIGN attribute
It is Used only when ALIGN is set to LEFT or
[ HSPACE = Pixels] RIGHT, It specifies amount of horizontal blank
7 (Optional)
space the browser should leave surrounding the
applet.
[ALT = Alternate_text ] Non _java browser will display this text where the
8 (Optional) applet would normally go.
Steps to adding an applet to HTML page
1. Insert an <APPLET> tag at an appropriate place in web page(in HTML file).
2. Specify the name of the applet‘s .class file.(CODE=[Link])
3. If the .class file is not in the current directory ,uses the codebase parameter to
specify
• The relative path if file is on the local system
• The URL of the directory containing the file if it is on a remote computer.
4. Specify the space required for display of the applet in terms of width and height in
pixels.
5. Add any user defined parameters using <PARAM> tags.
6. Add alternate HTML text to be displayed when a non java browser is used.
7. Close the applet declaration with the </APPLET> tag.
passing parameters to applet
<PARAM ...> tag is used to supply user defined parameters to applet.
Passing parameter to an appplet code using <PARAM> tag is similar to passiiing
parameters to the main() method using command line argument.
To pass and handles parameter ,do following:
1. Include appropriate <PARAM...> tag in HTML document.
2. Provide code in the applet to parse these parameters.
Parameters are passed to an applet when applet is loaded.
We can define init() method in applet to get hold of the parametes defined in
<PARAM> tags.
getParameter() method ,takes one string argument representing the name of program.
Each <PARAM...> tag has a name attribue and value attribute .
Inside the applet code ,the applet can refer to that parameter by name to find its value.
We can also change text to be displayed by an applet by supplying new text to the
applet through <PARAM ... > tag.
• E.g. :
<APPLET....... >
<PARAM name=color value=“red”>
<PARAM name=text value=“I like java!”>
</APPLET>
Example:
import [Link].*;
import [Link].*;
public class Helloparam extends Applet
{
String str;
public void init()
{
str=getParameter("string");
if(str==null)
str="java";
str="hello" + str;
}
public void paint(Graphics g)
{
[Link](str,10,100);
}
}
//save file in path “D:\javapro\[Link]”
<html>
<HEAD>
<! parameterized HTML file>
<TITLE > Welcome to java applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE=[Link] width=400 height=400 >
<PARAM NAME="string" VALUE= "Applet !">
</Applet>
</BODY>
</html>
//save file in path “D:\javapro\[Link]”
Output:
Displaying a numeric value
• In applet,we can display numerical values by first converting them into strings and
then using drawString() method of Graphics class.
• Example:
import [Link].*;
import [Link].*;
/*<applet code=[Link] height=400 width=400>
</applet> */
public class NumValues extends Applet
{
public void paint(Graphics g)
{
int val1=10;
int val2=20;
int sum= val1 + val2;
String s = "sum :" + [Link](sum);
[Link](s,10,100);
}
}
Write an applet program which takes two input values from user and
calculate sum of two values.
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="SumApplet" width=400 height=200></applet> */
public class SumApplet extends Applet implements ActionListener {
TextField t1, t2, result;
Button addButton;
public void init() {
Label l1 = new Label("Enter First Number: ");
Label l2 = new Label("Enter Second Number: ");
Label l3 = new Label("Sum: ");
t1 = new TextField(10);
t2 = new TextField(10);
result = new TextField(10);
[Link](false);
addButton = new Button("Add");
[Link](this);
add(l1);
add(t1);
add(l2);
add(t2);
add(addButton);
add(l3);
add(result);
}
public void actionPerformed(ActionEvent e) {
try {
int num1 = [Link]([Link]());
int num2 = [Link]([Link]());
int sum = num1 + num2;
[Link]([Link](sum));
} catch (Exception ex) {
[Link]("Invalid Input!");
}
}
Painting an applet
(Update, paint, repaint method)
• All three methods are defined in Component class.
• All the various controls and applets inhrit these methods.
1) paint ( ) method :
It determines that what is done when any item is redrawn.
It is called when anything needs to be redrawn.
All displayble entities have paint() method that they inherit from Component.
Interacive elements such as buttons ,are redrawn automatically no need to implement
a paint method for them.
paint() method is called whenever applet window is minimized or maximized or
overwritten.
2) repaint() method
If in the middle of some other method you realize that appearance of the component
should change,then you should change the values of hte instance variables and call the
components repaint() method.
This method tells that it should redraw the component as soon as as it gets chance(by
calling the paint() method)
repaint() method requests a redraw of an item or an entire [Link] then calls
update() method.
An applet can call repaint() method directly to update the window whenever necesary.
repaint() method has four forms :
1. public void repaint() :
This causes the entire window to be repainted.
2. public void repaint() (int left ,int top , int width ,int height):
Repaints only the rectangular part of the screen defined by x,y width and height .
3. void repaint(long mililseconds):
• Tries to call update for the number of milliseconds in the input argument.
• If update can’t be called by the end of the specified time ,repaint gives [Link]
error is thrown if the method gives up.
• This version of method used primarily for animations.
4. void repaint(long time,int x,int y,int width,int height) :
• It combines previous two repaint() versions so that only a portion of hte screen is
updated.
• If it can’t be done before the specified time elapses ( in milliseconds ),it is
skipped.
• When repaint() method is invoked on container ,such as an applet,the AWT takes
care of invoking update on all items in container.
3) update() method:
• The system does not actually call the paint() method,actually update() called
directly by the system.
• The built in update procedure first fills in the entire component with a
background color.
• then it calls the paint() method ,the paint() method draws on a rectanglar area that
has already been filled with the background color.
• update() method controls what happens when repaint is called;this method can be
overriden.
• update() method improves drawing performance along with paint method.
• update() method clears the current display and calls the paint() method.
• Syntax:
public void update( Graphics g)
{
paint ( g) ;
}
Example: update() ,patint() and repaint() method
import [Link].*;
import [Link].*;
public class PaintMethod extends Applet implements Runnable
/* <applet code="[Link]" width=200 height=400></applet> */
{
int counter;
Thread t;
public void init()
{
counter = 1;
t = new Thread(this);
[Link]();
}
public void run()
{
try
{
while (true)
{
repaint(); // Ask applet to redraw
[Link](1000); // 1 second delay
counter = counter + 1; // Increase counter
}
}
catch (InterruptedException e)
{
}
}
// Do not clear background → avoid flicker
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
showStatus("paint() and update() Method Demo");
// Even number
if (counter % 2 == 0) {
setBackground([Link]);
[Link]("Counter is Even: " + counter, 40, 100);
}
// Odd number
else {
setBackground([Link]);
[Link]("Counter is Odd: " + counter, 40, 100);
}
}
}