0% found this document useful (0 votes)
76 views14 pages

Chap11 Applets Final

The document provides instructions to modify an existing lesson document on applets. It asks to increase the chapter length to 13-14 pages, increase the word count of lessons to 3000-4000 words, include output of programs, remove bolding of terms, check and update the glossary and model questions, add more book references, and check for plagiarism after making changes. It provides the lesson document on applets and asks to make any required changes or modifications to it based on the instructions.

Uploaded by

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

Chap11 Applets Final

The document provides instructions to modify an existing lesson document on applets. It asks to increase the chapter length to 13-14 pages, increase the word count of lessons to 3000-4000 words, include output of programs, remove bolding of terms, check and update the glossary and model questions, add more book references, and check for plagiarism after making changes. It provides the lesson document on applets and asks to make any required changes or modifications to it based on the instructions.

Uploaded by

Rajan Sahota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Sir,

Increase chapter length. Its only10, make it 13-14 Pages.


A lesson must have 3000 – 4000 words in it.
Give output of programs.
Do not bold any terms.
Gloassary was having very few items, I have added some more. Kindly check it.
Model questions was having very few items, I have added some more. Kindly check it.
Add some more book names in References / Suggested Readingsgiven at last page.

After completing, check plagrisme at site : http://smallseotools.com/plagiarism-checker/

USE THIS DOCUMENT TO MAKE ANY CHNGES OR MODIFICATIONS or


ADDITIONS etc AS I HAVE MADE SOME CORRECTIONS IT IT.
PDCA-201
Applets
Unit-3. Lesson - 11 Applets

Chapter Index
Objectives
Introduction

 How Applets differ from Applications


 Preparing to write applets
 Building Applet Code
 Applet Life Cycle
 Designing a Web Page
 Applet Tag
 Adding Applet to HTML File
 Running the Applet
 Types of Applets
 Using Applet Applications
 Passing Parameters to Applets
 Summary
 Glossary
 Answers to Check Your Progress / Self Assessment Questions
 References / Suggested Readings
 Model Questions

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.

11.2 How Applets differ from Applications

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.

Check Your Progress / Self Assessment Questions


Ques 1. True / False : An applet does not require main( ) method?
Ques 2. True / False: Applets have limited access to the resources of the client machine?

11.3 Preparing to write Applets


To create an applet in Javait is requiredto import two java inbuilt packagesjava.applet.Appletand
java.awt.* in a user defined class. These packages are necessary because the Applets are not console-
based programs rather it runs on Window-based environment and interact with the user through GUI
(Graphical User Interface). The access type of the class must be public to make it accessible from the
HTML document. The class must be inherited from the Applet class of the applet package using the
keyword extends. The paint( ) method provided by the AWTpackagecanbe overridden to display its
output.The syntaxof creating an applet is:
import java.applet.* ;
import java.awt.* ;
public class AppletName extends Applet
{
// Applet code
}
11.4 Building Applet Code
To build an applet code, two packages java.awt and java.applet are imported in an applet class. The
applet code is shown below. The drawString( ) methodin the program shows the message: "Hello
World, Form a Simple Java Applet !" at location 50,25 in the browser window.
import java.awt.* ;

import java.applet.* ;

public class MyApplet extends Applet 

   public void paint(java.awt.Graphics g)

   {

        g.drawString("Hello World, Form a Simple Java Applet !",50,25);

     }

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.

Check Your Progress / Self Assessment Questions


Ques 3. Which packages are required to create an applet ?
Ques 4. Which class will be inherited to create an applet?

Applet Life Cycle


Every applet has five stages in this life cycle, each of which has a matching method. You can override
these methods to gain access to the life cycle of the applet's life. The five stages of an applet's life cycle
are shown in Fig. 11.1. The default implementation of these methods is provided which does nothing.
Applets need not to override all of the methods. Because applets run in a web browser, therefore these
methods are not called directly by the applet. The browser or applet viewer calls these methods at
appropriate times during the life cycle of an applet.

Figure 11.1. Life cycle of an applet.

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

Creating an executable applet


To create an applet executable, the applet program needs to compile that creates a class file using the
compiler javac. Create an HTML document and embed the class file in a web document using an
<applet> tag.Run the HTML document inside any Java enabled web browser.

Check Your Progress / Self Assessment Questions


Ques 5. Which method of the applet life cycle is used to draw output on the applet window?
Ques 6. Which method is used to initialize an applet?
Designing a web page

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.

Check Your Progress / Self Assessment Questions


Ques7.What is the use of <script> tag?
Ques 8. Which tag is used to insert an applet in a html document?

Adding Applet to HTML file


In order to run an applet in a Java enable web browser, the applet is included in a web page and is
treated as a part of webpage. For this purpose, create a web page using the minimum required HTML
tags as shown below:

<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.

Running the Applet


We can run the applet simply by opening the HTML file containing the applet in the browser and will
display web page and the applet running under it. There are two ways to run an applet:
1. Double click the HTML file and it will be loaded in a default web browser to display the output.
2. An alternative way to run the applet is with the utility appletviewer using the following command
at the command prompt:   appletviewer< html filename>. It will invoke a window with the applet
running inside it.

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.

Using Applet Applications

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.

Let’s take an example that illustrates the above concept.

import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet
{
String msg = "Hello Everybody..." ;

public void paint(Graphics g)


{
g.drawString(msg,40,20);
}
public static void main(String args[ ])
{
Applet helloApplet = new HelloApplet( );
helloApplet.init( ) ;
Frame window = new Frame("Here it runs as an Application") ;
window.setSize(300, 200) ;
window.add(helloApplet) ;
window.setVisible(true) ; // Make the window visible
}
}

Output

Passing Parameters to Applets

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:

<APPLET code = “applet class name” width = value height = value>


<param name = “p1” value = "v1">
<param name = “p2” value ="v2">
…………………
<param name = “pn” value = "vn">
</APPLET>

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);
}
}

Here is HTML code:

<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.

Answers to Check Your Progress / Self Assessment Questions


Check Your Progress / Self Assessment Questions
Ans1. True
Ans2. True
Ans3. Java.awt and java.applet
Ans 4.Applet class
Ans 5.void paint( )
Ans 6. void init( )
Ans 7. The <script> tag is used to declare scripting languages such as JavaScript.
Ans 8. <applet> tag
Ans 9. AppletViewer utility
Ans 10. String getParameter(“paramterName”)

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Core Java Volume I — Fundamentals (9th Edition), Prentice Hall
3. Programming Using Java, Meenu Sareen, Jyoti Book Depot, Jallandhar, India.

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?

You might also like