0% found this document useful (0 votes)
9 views21 pages

Java Applet Basics and Architecture Guide

This document provides an overview of applets in Java, including their architecture, lifecycle, and differences from applications. It explains how applets are small Java programs that run in web browsers, their initialization and execution processes, and the HTML APPLET tag used to embed them in web pages. Additionally, it includes examples and review questions to reinforce understanding of applet concepts.

Uploaded by

hakab18906
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views21 pages

Java Applet Basics and Architecture Guide

This document provides an overview of applets in Java, including their architecture, lifecycle, and differences from applications. It explains how applets are small Java programs that run in web browsers, their initialization and execution processes, and the HTML APPLET tag used to embed them in web pages. Additionally, it includes examples and review questions to reinforce understanding of applet concepts.

Uploaded by

hakab18906
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT I

1
Syllabus
Applet
Applet Basics Introduction, limitations of AWT. Applet architecture- HTML
parameter to Appletget, DocumentBase) and APPLET tag Passing
-

Buttons, Combo Boxes, Checkboxes, getCodeBase(), Japplet: lcons and Labels


Text Fields
Tabbed Panes, Scroll Panes, Trees Tables

Contents
1.1 Introduction

1.2 Applet Architecture

1.3 HTML APPLET Tag


1.4 Creating and Executing Applet
1.5 Passing Parameter to Applet
1.6 getDocumentBase) and getCodeBase()
1.7 Adding Controls to Applet
1.8 Multiple Choice Questions

(1-1)
1 . 1 introduction
be used in internet.
Applets
environment.
are the small Java programs
that can

etworking
transferred over the internet from mputer to another
one computer to.

These programs can be


web browsers.
and can be displayed on various
arithmetic operations, disnla.
applications of applets are in performing
.Various
animation and so on.
playing
graphics, playing sounds, creating
Following are the situations in which we
need to use applet-
1. For displaying the dynamic web pages we need an applet. The dynamic
web
page is a kind of web page on which the contents are constantly changino t.
For
example an applet that can represent the sorting process of some numbers
During the process of sorting the positions of all the elements is changino

continuously.
2. If we want some special effects such as sound, animation and much. more then
the applets are used.
3. If we want a particular application should be used by any user who might be
located remotely. Then in such situation the applets are embedded into the web
pages and can be transferred over the internet.
Difference between Applet and Application
Sr. No. Applets Applications
1 Applets do not have main method. On
APpication programs have main meth0d
loading of applets some methodssof
Withinthe mainmethodthe call toanother
appiet class get called automatically.
methods of Java class is given.
2. Applets cannot run independently.
Appications program run independently
They can be either embedded in web
page or can be run
using appletviewer.
3. Applets cannot be read from file.
Application programs make useof I/O
Similarly appletscan not write to files functions and can read afile orwritetofile
Applets cannot communicaie with
Java programs can communicate with other
others on the network.
programs in distributed environment.
5. Appleis cannot execute any program on local
Applications can execiute a program on
local computer.
çomputer,
TECHNICAL PUBLICATIONS an
up-thrust for knowledge
Advanced JAVA Programming
1-3
Review Question Applet
1.
Differentiate applet and application with any four
points.
1.2 Applet Architecture
There are various methods which
typically used are
in
applet for
termination purpose. These methods are: initialization and
1. Initialization

2. Running state

3. Idle state
4. Dead or
destroyed state (Refer Fig. 1.2.1 for applet's life cycle)
Applet
loaded
Borm init()

start() Applet
destroyed
Stopl)
Running ldle
destoy() End
Daad

Start()
Paint() Exit
browser

Fig. 1.2.1 Applet's life cycle


When applet begins, the AT calls
following methods in sequence -

a) init()
b) start() )paint()
When applet is terminated
following method are invoked in sequence.
a) stop0 b) destroy0
1. Initialization state

When applet gets loaded it enters in the initialization state. For this
purpose the
init() method is used. In this method
you can initialize the
required variables. This
method is called only once initially at the execution of the
program. The can syntax
be,
Public void init()

Iinitialization of variables

TECHNICAL PUBLICATIONS an
up-thrust for knowledge
1-4
Advanced JAVA Programming

initialization can bepertormed such aSs .


In this method various tasks of
1. Creation of objects
needed by applet
values
2. Setting up of initial
3. Loading of image

4. Setting up of colors.
2. Running state

When the applet enters in the running


state, itinvokes the start() method
of. Appla
class.
only after the init
method. After stopping the applet
when Ne
u.
This method is calied
method is invoked. The syntax h
can be
restart the applet at that time also this
public void start()

3. Display state
Applet enters in the display state when it wants to display some output. This ma
happen when applet enters in the running state. The paint() method is for
is
displaying or drawing the conternts on the screen. The syntax
public void paint(Graphics g)

An instance of Graphics class has to be passed to this function as an argument. In


this method various operations such as display of text, circle, line are invoked.

4. Idle state
This is an idle state in which applet becomes idle. The stop() method is invokeu

when we want to stop the applet. When an applet is running if we go to an ther

page then this method is invoked. The syntax is


public void stop()

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Applet
Advanced JAVA Programming 1-5

5. Dead state
method
to be dead then it
is removed from memory. The
When applet is said
to
w e want to
terminate applet completely and want
invoked when
destroy() is
remove it from the memory.

public void destroy()

to destroy method.
I t is a good practice
to call stop prior

Review Questions
1 Describe following states of applet life cycle:
a) Initialization state. b) Running state. c)Display state.
2. Explain applet life cycle with suitable diagram.

1.3 HTML APPLT Tag


The <APPLET> tag can be specified with the help of various attributes. Thesee
attributes help to integrate the applet into overall design of the web page.
. Various attributes of APPLET tag are -

Attribute Description
CODEappletfilename The specified applet can be loaded in the web page. This
attribute must be specified in order to embed the applet in the

HTML file.

WIDTH pixels This attribute specifies the width and height of the applet.
HEIGHT=pixels
ALIGNalignment This attribute is for specifying the alignment. Various
alignments are TOP, BOTTOM, LEFT, RIGHT, MIDDLE,
ABSMIDDLE, ABSBOTTOM, TEXTTOP and BASELINE.
This is
an optional attribute.

CODEBASE= codebase URL It specifies the name of the directory in which the applet is
stored. This attribute is
required when the attribute is not there
in the current
waorking directory. This is an
optional attribute.

TECHNICAL PUBLICATIONSan up-thrust for


knowledge
1-6 Applet
attribute is used.t
v A AVA PrOgrainming

RIGHT this
this attribute
either LEFT or
ALIGN is
When
horizontal
lank
blank spaces the brow
HSTACE= pixels amount of
the
specifies
. This is an optional attribute
around the applet.
should leave

BOTTOM this attribitatis used.


is either TOP or It
When ALIGN
VSPACE = pixels
of verhical
blank spaces the browser hould
amount
specifies the
the applet.
This is an optional attribute
leave around

can display the alternate text in Dlaco.


ce of
The non Java browser
ALT=alternate text
applet. This is
an optional attribute.

Review Questions
available in < applet> tag.
[Link] all attributes
with its major attributes only.
2 Explain <applet> tag
3. Describe the folloving attributes ofapplet:
(i) Codebase (i) Alt (ii) Width(iv) Code

4. Explain any four applet tag.

1.4 Creating and Executing Applet


1.4.1 Creating an Applet
Normally the applet code makes use of two classes - Applet and Graphics.

For the Applet class the package [Link] is required. This class provides the
applet's life cycle method such as init(), start() and paint().
The Graphics class is supported by the package [Link].
Here is a simple applet.
Example Program

This is my First Applet program

import [Link].";
import [Link].";
public class FirstApplet extends Applet

public void paint(Graphics g)

[Link]( This is my First Applet",50,30)

TECHNICAL PUBLICATIONS an up-thrust for knowledge


1 - 7
Advanced JAVA Programming Applet
Program explanation
. I n above given small applet program, the main intension is to display the message
"This is my First Applet". Let us start from the beginning of the program-
.The first three lines represent a comment statement.

Then next comes


import [Link].;
import [Link]. *;

W e always need these two packages to be imported in the program. The [Link]
package consists of java awt classes. Here awt stands for abstract window toolkit.
The AWT provides the support for window based graphical interface such as for
drawing screen, windows, buttons, text boxes, menus and so on. The other
imported package is [Link]. This is essential because we need to use Applet
class in our applet program which is included in [Link] package.
The functionalities that are required to run applet inside the web browser are
supported by [Link].
Then comes
Public claSs FirstApplet extends Applet
The class FirstApplet is a subclass of class Applet. Hence the keyword extends is
used. Java requires that your applet subclass (here it is FirstAplet) should be
declared as public. Hence is the declaration!
W e have then defined a method

Dublic void paint(Craphics g


This method is used to paint something on the and it
can be text, line, circle,
screen
rectangle or anything. Thus paint is a method which provides actual appearance on
the screen. And this method
requires a parameter to be passed as an object of class
graphics. Therefore an object g of class Graphics is passed.
Using this object the method drawString of Graphics class is invoked. [Note that
Graphics class is a part of [Link] package]
[Link]("This is my First Applet",50,30);
T o method
drawString, firstly we have passed string which
a we want to be
displayed, then 50 and 30 represents the position of the string on the screen i.e. x
and y positions
respectively.

TECHNICAL PUBLICATIONSan up-thrust


for knowledge
1-8
Advanced JAVA Programiming
Applet
Executing an Applet
1.4.2
There are two methods of executing an applet program-
1. Adding Applet to HTML File
2. Using Appletviewer tool
Let us discuss these methods in detail.

[Link] Adding Applet to HTML File


Following are the steps that need to be followed for adding applet to HTMI.
file.
Step 1: Write a Java applet program in a notepad. The code is as follows:

Java Program[[Link]]

This is my First Applet program

import [Link].";
import [Link]."
public class FirstApplet extends Applet

public void paint(Graphics g)

[Link]("This is my First Applet",50,30)

Step 2: Compile your applet source program using javac compiler, i.e.
Diltest>javac [Link]
Step 3: Write following code in notepad/wordpad and save it with filename and
extension .html. For example following code is saved as
Exe_FirstApplet.html, The code is
<html>
<body>
applet code="FirstApplet width=300
height 100>
/applet>
</body>
</html>
For
embedding the applet in the HTML document the <APPLET>
tag is used. i
APPLET> tag supplies the name of the
load the
applet to be loaded. we ant
Suppose va
applet FirstAppletprogram in the web
page then the applet tag wu e,

TECHNICAL PUBLICATIONS a n
up-thrust for knowledge
Applet
Advanced JAVA Programming 1-9
<APPLET CODE= [Link]

WIDTH = 500

HEIGHT = 300

</APPLET>

browser to load the comnpiled code of applet


. The HTML code tells the web
Note that this class ile must be present in the same
[Link].
is stored.
directory where the web page
web browser, This will cause to execute your html
Step 4 Load html file with some

file. It will look like this


-

wwwwwe
EDtest\Exe FirstApplethm
Edit View Favorites Toos Help
Fle
Seach Favorites
*********q************
Go Lis Note this
Adress 1E 0:testExe [Link]
Search Web URL

This is my First Afpplet

Applet FirstApplet *erted My Computer

[Link] Embedding Applet Code in Java


W e can embed the applet code in Java using comment statements. It is as shown in
following illustration.
Step 1: Write Java Program as given beloW.

This is my First Applet program

[Link].
import [Link].
Embedded Applet in
<applet code-"FirstApplet" width=300 height=100
</applet> Java
public class FirstApplet extends Applet

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


1-10
AdvancedJAVA Programming
Apple
public void paint (Graphics g)

First Applet",50,30);
[Link]("This is my

of the
I n above code we have added applet code at the beginning program.
am.
width=300 height=100>
applet code="FirstApplet'

</applet
.This will help to understand Java that the source program 1S an applet wi#
wit hthe
name FirstApplet.

Step 2: By this edition you can run your applet program merely by Appletia..
iewer
command.
D:1test>javac [Link]
D:test> Appletviewer [Link]

And we will get

LApplet Viewer:FirstApplet
Applet wwwwwww

This is my First Applet

Applet started.

Example1.4.1 Define applet. Write a program fo createan applettodisplay inessag


"Welcome to java applet
Solution: [Link]

This is my First Applet program

import [Link].";
import [Link].

<applet code="FirstApplet' width=300 height 100>


lapplet
public class FirstApplet extends Applet

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


Applet
Advanced JAVA Programming 1-11

g)
public void paint(Graphics

[Link]("Welcome to
Java Applet",50,30);

Output

Applet Viewer: FirstA


Applet

Welcome to Java Applet

Applet started.

1.5 Passing Parameter to Applet


Parameters are passed to applets in NAME=VALUE pairs in <PARAM tags
between the opening and closing APPLET tags.
There can be any number of <PRAM> tags inside APPLET tag.

Inside the applet, you read the values passed through the PARAM tags with the
getParameter() method ofthe Applet class.
The program below demonstrates this idea-
Example 1.5.1 Hoe can parameters be passed toan applet ? Write an applet to accept user name
intheform ofparameter and print "Hellousername>
Solution:
import [Link];
import [Link];
applet code="WelcomeParam" width=200 height=200>
Sparam name-"Usemame' value='Parth'
s/applet

public class WelcomeParam extends Applet

String msg
public void init()

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


1-12 Applet
4, v e 4 V A Programmin9

msg getParameter("Username");

"Welcome"
+ msg
msg=

paint(Graphics g)
public void

g . d r a w S t r i n g ( m s g , 5 0 , 5 0 ) ;

Output

App
Applet

Welcome Parth

Applet started

tagand
Example1.5.2 applet progran that accepts trw0input,sriigs usingParam>
Write an
concatenate the strings anddisplay it in
statusS window.

Solution: [Link]
import [Link]."
import [Link].";

APPLET code="TwoStrings" width="300" height="100


<PARAM name="str1" value="First>
<PARAM name="str2" value="Second">
</APPLET>
/
public class TwoStrings extends Applet

public void paint(Graphics g)

String s1 = [Link]('str1");

String s2 = [Link]('str2");

String s3;

TECHNICAL PUBLICATIONS an
up-thrust for knowledge
Advanced JAVA Programming 1- 13
Applet
s3=s1+52;
showStatus(s3);

Output

Applet Viewer: TwoS. O X


Applet

Note that the


strings are
displayed here

FirstSecond

Example 1.5.3 Design an applet which accepts username as a parameter för html page and
display number of characters fron it.

Solution: Step 1: Create HTML page as follows -


[Link]
<html>
head
Stitle> Parameter Demo </title>
</head>
applet code "[Link]' width =300 height =300>
<PARAM name="uname" value="Chitra">
</applet>
S/html
Step 2: Create Java program for
the applet class as follows-
[Link]
import [Link]."
import [Link].
public class LengthDemo extends Applet

public void paint(Graphics g)

String str =
[Link]('uname");
int len;
len=[Link]();

TECHNICAL PUBLICATIONS -an up-thrust


for knowledge
1-14
4cenced JAVA Programming
"+len;
Applet
msg= "The length of string 'Chitra' is:
String
[Link](msg,50,30);

Compile the program created in step 2 using following comma


Step 3 on
Command prompt
D:\>javac [Link]

Step 4:Open the web browser and type the


name of the html file created in sten 1. The
output will be
-

Applet

The length of string 'Chitra' is: 6

Applet started.

Example 1.5.4 How to pass parameter to an applet? Write an appletfo accept AccountNo and
balance in form of parameter and print message "loru balance if the balance is less than 500

Solution:
import [Link]."
import [Link].";

APPLET code= "BalanceChk' width="300" height="100">>


<PARAM name ="AccNo" value= 1001>
<PARAM name="Balance' value=300>
</APPLET>

public class BalanceChk extends Applet

public void paint{Graphics g)

balance
t
[Link]([Link]("Balance");
=

.[Link] < 500)


g. drewString("'Low Balance",50,30);

cre [Link]('Sufñcient Balance",50,30);


Advanced JAVA Programming
1- 15 Appier
Output

Applet Viewer: Balan..

Applet
Low Balance

Applet started.

Review Questionis
with suitable example.
1. Explain <PARAM> Tag ofapplet
with an example:
2. Explain following methods for applet
1) Passing parameter to applet

2) Embedding <applet> tags in java code.

1.6 getDocumentBasel) and getCodeBase()


return the
are the two methods that
The getDocumentBase) and getCodeBase0
names of the directories. The getDocumentBase()
is the name of the directory
The getCodeBase() is the name
which contains the HTML file that starts the applet.
is loaded.
of the directory that contains the class file of the applet
URL getCodeBase0: Gets the base URL
o URL getDocumentBase(): Gets the URL of the document
in which the apple is
embedded.

two directories.
Following applet program shows the demonstration of these
Java Program
[Link].*;
import [Link].
import [Link].";

<applet code="DocBaseCode" width=500 height=300>


s/applet>

public class DocBaseCode extends Applet

public void paint(Graphics g)

TECHNICAL PUBLICATIONS- an up-thrust far knowledge


Advanced JAVA Programming 1-16
Applet
String msg
WgetCodeBase Methocd
URL appletCodeDir = getCodeBase():

msg = "Applet Code Base: "+[Link]():

[Link](msg, 20, 50);

/getDocumentBase Method
URL appletDocDir = getDocumentBase():

msg "Applet Document Base: "+[Link](


[Link](msg, 20, 80);

Output

Applet Viewer: DocBase Code


Applet *****

*************************"**********************************"**"* "* *********"****************** V

Applet Code Base:


file:/home/puntambekar
Applet Document Base:
file:/home/puntambekar/DocBasecode java

Applet started.
[Link]

1.7 Adding Controls to Applet


We can add various controls
such textbox, Push Button, Radio button,
as
to the Check Dox
applet. Let us understand this with illustrative examples
1.7.1 Buttons
The Button cdlass is
used to add the labeled button to the applet. The
button ispassed as parameter to it. The
a caption o
Button syntax is
button_object=new Button(caption string)
TECHNICAL PUBLICATIONS-an
up-thrust for knnwlanina
1 17 Applet
Advanced JAVA Programming

.Using add method we can add the button control on the applet window. Following
how to add button to the applet.
program shows

Example Program
import [Link].":
import [Link].";

import [Link].";

/
code="Button1" width=350 height=200>
<applet
</applet>

class Button1 extends Applet


public

Button button=nevw Button("Click Me"):


public void init()

add(button);

Output

Applet Viewer Bu
Applet

Click e

Applet started.

1.7.2 Text Fields


The
TextField class allows to add the single line text. Following program show
how to add a textfield control to the applet.

Example Program
import [Link].
import [Link].";
import [Link].";

<applet code="TextFieldDemo" width=350 height=200>


ne
</applet>>

TECHNICAL PUBLICATIONS an up-thrust for knowedge


1- 18 Applet
Programming
4 ceO JA VA
TextFieldDemo
extends Applet
public class

How are you?


);
TextField tf=new TextField("Hello,
public void init()

add(tf);

Output

Applet Viewer Textfie..

Applet

Hello, How are you?

Applet started.

1-7.3 Combo Boxes


Combobox is a dropdown list. It forces the user to select only one element from the
list. It is easier to change the element of the list. It is a basically a Choice control.
Hence it is created using Choice0 class.
Foilowing program demonstrates the use of combox control.

Java Program|[Link]]
import [Link].";
import [Link].";

<applet code="ComboBoxDemo" width=350 height


200
/applet

public class ComboBoxDemo extends Applet

Choice city=new Choice();


public void init()

TECHNICAL PUBLICATIONS an
up-thrust for knowledge
Advanced JAVA Programming
1-19 APP et
[Link]('Pune");
[Link]( Mumbai");
[Link]('Delhi");
[Link](Kolkata");
add(city):

Output

Applet Vlewer: ComboBoxDemo

Applet

Mumbai
Pune
Mumbai
Delhi
Kolkata
wwwwwww

Applet started.

1.7.4 Checkboxes
The Checkbox class is used to create check boxes. It is used to tum an option true or
false. Following program shows the use of checkbox.

Example Program
import [Link].
[Link].";
import [Link].";
capplet code="CheckBoxDemo" width=350 height=200>
</applet
public class CheckBoxDemo extends Applet

TECHNICAL PUBLICATIONS an
up-thrust for knowledge
4 i e r c e oJAVA Programming
1-20 Applet
cb1=new
Checkbox("Adhar Card",true);
Checkbox

cb2=new
Checkbox("'Pan Card')
Checkbox

public void init()

add(cb1);

add(cb2);

Output

X
Applet Viewer CheckB.

Applet
Card
Adhar Card Pan
*************************

Applet started.

1.8 Multiple Choice Questions


Q.1 On which side applet always executed ?
a Server side
b Client side
Q.2 Which method of the Applet class displays the result of applet code on sereen ?
a run() method
b paint() method
c drawString) method d main) method
Q.3 Applet can be embedded in
a HTML document
bword document
cgiffile rtf file
TECHNICAL PUBLICATIONS an
up-thrust for knowledge
Advanced JAVA Programming
1-21 Applet
Q.4 Which of the following is true about applet ?
a Applets do not have main() method.
b Applets must run under appletviewer or web browser.
cThe user I/O is not performed using Java's stream I/O class.
d All of these.
Q.5 Executable applet is
aapplet file b java html
C java file [Link] file
Q.6 Which object can be constructed to show any number of choices in the visible window ?
a Labels bChoice
List d Checkbox
Q.7 The drawString method of defined in
a [Link] [Link]
[Link] [Link]
Q.8 Which class
provides many methods for graphics programming?
a [Link] b [Link]
[Link] d None of these
Q.9 When we invoke repaint) for a
[Link] object, the AWT invokes the
method:
a draw) bupdate0
c show) d paint(
Q.10 Which method executes only once?
a start() b stop0
init) d destroy0
Q.11 What does the following line of code do?
Textfield text =
Textfield(20);
new

a Creates text object that can hold 20 rows of text.


b Creates text object that can hold 20 columns of text.
c Creates the object text and initializes it with the value 20.
d This is invalid code

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge

You might also like