Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.

 

Java Applet :

Applet is a special type of program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.

Applets are basically small java programs which can be transported from one computer from another computer in the network.

Life cycle of Java Applet:

Or
Explain the life cycle  of an applet with  example?
Or
Describe different stage of life cycle of an applet?

Applet is initialized. (Initial state)
Applet is started.(running state)
Applet is painted.(Display state)
Applet is stopped.(idle or stoped state)
Applet is destroyed.(dead state)


When an applet is executed within the web browser or in an applet window, it goes through the four stages of its life cycle: initialized, started, stopped and destroyed.These stages correspond to the applet methods init(), start(), stop() and destroy() respectively. 

-->All above mention methods are defined in java.applet.Applet class except paint() method.
-->paint() method is defined in java.awt.Component class.



Following are the methods of the life cycle :
1) init() method
2) start() method
3) paint() method
4) stop() method
5) destroy() method

1) init() :
-->It is used to initialize the Applet. It is invoked only once.
-->This method is called before all the other methods.
-->It is used to initialize the applet each time it is reloaded. Applets can be used for setting up an initial state, loading images or fonts, or setting parameters.

For example:
public void init()
{
  //code here
}


2) Start() :
-->This method is automatically called after the browser call the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other
pages.
public void start()
{
____________________
____________________
(Action)
}


3) Stop() :
-->An applet comes in idle state when its execution has been stopped either implicitly or
explicitly.
-->An applet is implicitly stopped when we leave the page containing the currently running applet.
-->An applet is explicitly stopped when we call stop() method to stop its execution.
So, this method called repeatedly in the same applet.

public void stop()
{
____________________
____________________
(Action)
}


4) Destroy():
--> This method is only called when the browser shuts down normally. It is called only once.
-->It is called just before an applet object is removed from the memory.

public void destroy()
{
____________________
____________________
(Action)
}


5) Paint():
-->It is invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser.
-->The paint() method is actually inherited from the java.awt.Component
-->It provides Graphics class object that can be used for drawing oval, rectangle etc.
The Component class provides 1 life cycle method of applet.

public void paint(Graphics g):
it  is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
The paint() method is used for displaying anything on the applet paint() method takes an argument, an instance of class graphics.
The code given can be as follows:
public void paint(Graphics g)
{
//message
}
where Graphics class contains the member functions that can be used to display the output to the browser.
text String, the drawString() method is used.
g.drawString(String s, int x, int y)

where x and y are the coordinate positions on the screen and s is the string to be output.


Write a java program to demonstrate applet life cycle.


import java.applet.*;
import java.awt.*;

public class MyApplet extends Applet
{
  public void init()
  {
    System.out.println("Applet is initialized");
  }
  public void start()
  {
    System.out.println("Applet is started");
  }
  public void stop()
  {
    System.out.println("Applet execution is stopped");
  }
  public void paint(Graphics g)
  {
    System.out.println("Painting the Applet");
  }
  public void destroy()
  {
    System.out.println("Applet is Destroyed");
  }
}

Program (MyApplet.html)
<html>
<head>
<title>Applet Life Cycle</title>
</head>
<body>
<applet code = "MyApplet.class" width = "300" height = "300">
</applet>
</body>  
</html>


Develop an Applet in java that displays a simple message.

Or

Develop an applet program to print HelloWorld .

Or

Develop an simple applet program to display  welcome message.


MyApplet.java:
import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code="MyApplet" width = 200 height= 100>
</applet>
*/
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome (HelloWorld)", 50, 25);
}
}


How are applets differ from application programs explain with example?
Or
differences between applets and applications.
Or
Differentiate between Applet and Application .


Applet program:

1 .Applet does not use main() method for 
initiating execution of
code.

2 .Applet cannot run independently.

3 .Applet cannot read from or write to files in local computer.

4 .Applet cannot
communicate with other servers on network.

5 .Applet cannot run any program from local computer.

6 .Applet are restricted from using libraries
from other language such as C or C++.

7.Applets are event driven.

8.Applets are small program.

9.parameters to the applet are given in the  html file.


Application program:

1.Application uses main() method for initiating execution of code.

2.Application can run independently.

3.Application can read from or write to files in local computer.

4.Application can communicate with other servers on network.

5.Application can run any program from local computer.

6.Application are not restricted from using libraries from other
language.

7. Applications are control driven.

8.Applications are larger program.

9.parameters to the application are given at  the  command prompt.


Hierarchy of Applet

Applet class extends Panel. Panel class extends Container which is the subclass of Component.




How to create an Applet?

Applets can be created in two ways:

--> java.applet.Applet class:One ways is extending the Applet class from java.applet.* package.

--> javax.swing.JApplet class: Another way is extending the JApplet class of java.swing.* package.

All applets inherit the super class "Applet".


How to run an Applet ?

-->There are two ways to run an applet :

1)Using HTML file

2)Using  AppletViewer tool


1) Using HTML file
Example using HTML file :

// MyApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",200,200);
}
}
//MyApplet.html
<html>
<body>
<applet code="MyApplet.class"
width="300" height="300">
</applet>
</body>
</html>


2) Using AppletViewer tool

Example using AppletViewer tool :

//MyApplet.java
/*
<applet code="MyApplet.class" width="300" height="300">
</applet>
*/

import java.applet.Applet;
import java.awt.*;

public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",200,200);
}
}

To run these above two code write following code in prompt :
c:\>javac MyApplet.java
c:\>appletviewer MyApplet.java


Who is responsible for running the applet programs?

Java Plug-in software.



Passing parameters to an Applet :

Or
Input passing to an Applet :


We can supply user defined parameters to an applet using the <param> Tag of HTML.
Each <param> Tag has the attributes such as "name" , "value" to which actual values are assigned. Using this
tag we can change the text to be displayed through applet. We write the <param> Tag as follow:

<param name="name1" value="Hello Applet" >
</param>
Passing parameters to an Applet is something similar to passing parameters to main() method using command line arguments. 


-->To set up and handle parameters, we need to do two things:

1. Include appropriate <param> Tag in the HTML file
2. Provide the code in the applet to take these parameters.

Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page.

The param tag(<parma name=" "
value=" "> </param>) is used to pass the parameters to an applet. The
applet has to call the getParameter() method supplied by the java.applet.Applet parent class.


Ex1: Write a program to pass employee name and id number to an applet.

import java.applet.*;
import java.awt.*;

/*
<applet code="Employee.class" width = 600 height= 450>
<param name = "t1" value="omkar dengi">
<param name = "t2" value ="101">
</applet>
*/
public class Employee extends Applet
{
String n;
String id;
public void init()
{
n = getParameter("t1");
id = getParameter("t2");
}
public void paint(Graphics g)
{
rawString("Name is : "
+ n, 100,100);
g.drawString("Id is :
"+ id, 100,150);
}
}


Ex2: Write a program to pass two numbers and pass result to an applet.
Or
Write a program to pass two numbers and perform addition of two numbers result to an applet.

import java.awt.*;
import java.applet.*;

/*
<APPLET code="Sum" width="300"
height="250">
<PARAM name="a" value="5">
<PARAM name="b" value="5">
</APPLET>
*/
public class Sum extends Applet
{
String str;
int a,b,result;
public void init()
{
str=getParameter("a");
a=Integer.parseInt(str);
str=getParameter("b");
b=Integer.parseInt(str);
result=a+b;
str=String.valueOf(result);
}
public void paint(Graphics g)
{
g.drawString(" Addition is : "+str,0,15);
}
}


Ex3: Write a java program to find the maximum of 2 number using parameters in applet.

import java.awt.*;
import java.applet.*;
import java.io.*;

/*
<applet code="AppletMax" width=500 height=500>
<param name="a" value="10">
<param name="b" value="20">
</applet>
*/

public class AppletMax extends Applet
{
int a;
int b;
int c;
String str;

public void start()
{
String s1;

s1 = getParameter("a");
a = Integer.parseInt(s1);

s1 = getParameter("b");
b = Integer.parseInt(s1);
}

public void paint(Graphics g)
{
if (a > b)
c = a;
else
c = b;

g.drawString("a is " + a, 10, 50);
g.drawString("b is " + b, 10, 100);
g.drawString("maximum of two num is " + c, 10, 150);
}
}


Ex4: How can parameter be passed to an applet? Write an applet to accept user name in the form of parameter and print ‘Hello<username>’.


Passing Parameters to Applet
User defined parameters can be supplied to an applet using <PARAM…..> tags.
PARAM tag names a parameter the Java applet needs to run, and provides a value
for that parameter.
PARAM tag can be used to allow the page designer to specify different colors, fonts,
URLs or other data to be used by the applet.
To set up and handle parameters, two things must be done.
1. Include appropriate <PARAM..>tags in the HTML document.
The Applet tag in HTML document allows passing the arguments using param tag.
The syntax of <PARAM…> tag
<Applet code=”AppletDemo” height=300 width=300>
<PARAM NAME = name1 VALUE = value1>
</Applet>
NAME:attribute name
VALUE: value of attribute named by corresponding PARAM NAME.
2. Provide code in the applet to parse these parameters.
The Applet access their attributes using the getParameter method. The syntax is :
String getParameter(String name);


import java.awt.*;
import java.applet.*;
public class HelloUser extends Applet
{
String str;
public void init()
{
str = getParameter("username"); // Receiving parameter value
str = "Hello "+ str; //Using the value
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>


OR


import java.awt.*;
import java.applet.*;
/*<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>*/
public class HelloUser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}


Advantages of Applet

There are many advantages of applet. They are as follows:

1.Applets provide dynamic nature for a webpage.
2. Applets are used in developing games and animations.
3.Writing and displaying (browser) graphics and animations is easier than
applications.
4. In GUI development, constructor, size of frame, window closing code etc. are not required
5.It works at client side so less response time.
6.Secured
7.It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.


Drawback of Applet
Plugin is required at client browser to execute applet.


TYPES OF APPLETS
There are two types of Applets.
1)The first type is created is based on the Applet class of java.applet package. These applets use the Abstract Window Toolkit(AWT) for designing the graphical user interface.

2)The second type of type of the Applets are based on the Swing class JApplet. The swingApplets use the swing classes to create Graphical User Interface.
The JApplet inherits the properties from the Applet, so all the features of the Applet are available in the JApplet.

Applets are of two types:
1) Local Applets
2) Remote Applets

1) Local Applets:
i) An applet developed locally and stored in a local system is called local applets.

ii) local system does not require internet. We can write our own applets and embed them into the web pages.

iii)Example:
<applet  codebase="Path" code="abc.class" width=400 height=400>
</applet>


2) Remote Applets:
i) An applet developed locally and stored in a remote system is called remote applets.
The applet that is downloaded from a remote computer system and embed applet into a web page.

ii) The internet should be present in the system to download the applet and
run it.
To download the applet we must know the applet address on web known as Uniform Resource Locator(URL) and must be specified in the applets HTML document as the value of CODEBASE.

iii) Example:
<applet  codebase="URL" code="abc.class" width=400 height=400>
</applet>


Methods of Applet class :

An Applet class contains several methods that help to control the execution of an applet.

1.public void init(): is used to initialized the Applet. It is invoked only once.

2.public void start():it  is invoked after the init() method or browser is maximized. It is used to start the Applet.

3.public void stop(): it is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.

4.public void destroy(): it is used to destroy the Applet. It is invoked only once.

5.boolean isActive( ) : Returns true if the applet started else returns False.
Determines if this applet is active.

6.void resize(int width, int height):
Resizes the applet according to the dimensions specified by width and height.

7.void play(URL url) :Plays the audio clip at the specified absolute URL.

8.String getParameter(String paramName)
Returns the parameter associated with paramName. If not found then return NULL.


List out the attributes of applet tag.
Or

Give the attributes of applet tag.

The <applet> tag instructs the browser
that an applet has to be loaded and executed using the Java Runtime Environment (JRE). It takes
three mandatory attributes: code, width, and height. The code attribute specifies the class file for this applet to be instantiated. The width and height attributes indicate the width and height, respectively.

The <applet> tag takes several other optional attributes. It takes the following general form:
<applet
code='appletClassFile'
[codebase='URLOfCodeBase']
[alt='altervativeText']
[name='NameOfApplet']
width='width of Applet window in pixels'
height='height of Applet window in pixels'
[align='alignment']
[vspace='pixels']
[hspace='pixels']>
The optional attributes are shown in square brackets.
Let us discuss the functionality of each of these attributes.

1)code — This attribute specifies the name of the class file (without the extension .class) that
contains the applet’s byte code.

2)codebase — It specifies the base URL to be searched for the applet’s executable class file.
If nothing is mentioned, the directory from where the HTML document containing this applet
was downloaded is assumed. In such cases, you must put the applet’s class file and the HTML
document in the same directory. However, different URLs may also be used with some restrictions.

3)alt — It specifies a message to be displayed if the browser has been able to understand the
applet, but has failed to execute it for some reason such as the user turning off the applet.

4)name — This attribute specifies a name for an applet instance. Other applets use this name to
find it and communicate with it.

5)width — It is the width of the applet window in pixels.

6)height — It is the height of the applet window in pixels.

7)align — It is used to adjust the position of an applet with respect to the surrounding text and
images. It can have the following values:
• left — It puts the applet on the left side of the page and causes text to wrap around it.
• right — It puts the applet on the right side of the page and causes text to wrap around it.
• top — It aligns the top of the applet with the top of the text.
• bottom — It aligns the bottom of the applet with the bottom of the text.
• middle — This value works differently in different browsers. In some browsers, it aligns the middle of the
text with the middle of the applet. In some other browsers, it aligns the bottom of the text with the middle of
the applet window.
• baseline — It aligns the bottom of the applet with the baseline of the text. The baseline is the bottom line
of characters such as a, b, c, d, and e. Some letters such as g, j, and p dangle below this baseline.

8)vspace — It specifies the space to be left above and below the applet window, in pixels.

9)hspace — It specifies the space to be left on the left and right of the applet window, in pixels.


Develop an applet in java that receives an integer in one text field, and computes its factorial value and returns it in another text field, when the button named “Compute” is clicked.


Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MyAppletFact extends Applet implements ActionListener
{
Label   l1,l2;
Button b1;
TextField t1,t2;
public void init()
{

setLayout(new FlowLayout(FlowLayout.LEFT));
l1 = new Label(“Enter the number”);
l2 = new Label(“Result:Factorial Value is:”);
t1 = new TextField(30);
t2 = new TextField(30);
b1 = new Button(“Compute”);
add(t1);
add(t2);
add(l1);
add(l2);
add(b1);
l1.setBounds(50,100,150,30);
l2.setBounds(50,150,150,30);
t1.setBounds(250,100,150,30);
t2.setBounds(250,150,150,30);
b1.setBounds(230,240,100,30);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()==”Clicked”)
{
int n= Integer.parseInt(t1.getText());
int fact =1;
for (int i= 1; i<=n; i++)
{
fact=fact*i;
}
t2.setText(String.valueOf(fact));
}
}
}
/*
<applet code=”MyAppletFact″ width =1000 height =1000>
</applet>
*/



Write a Java Program to display Audio Clip in Applet.

AudioDemo.java
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
<applet code="AudioDemo.class" width=400 height=400>
</applet>
*/

public class AudioDemo extends Applet
{
AudioClip ad;
public void init()
{
ad=getAudioClip(getDocumentBase(),"kuhu kuhu bhole koyaliya.au");
}
public void start()
{
ad.loop();
}
public void paint(Graphics g)
{
g.drawString("Are you Hearing the sound",20,20);
}
public void stop()
{
ad.stop();
}
}


Write a applet program to create simple GUI consist of Button, Radio Button, TextField, Checkbox and Label.


Program:

import java.awt.*;
import java.applet.*;
/*
<applet code="AppletComponent.class" width=400 height=400>
</applet>
*/
public class AppletComponent extends Applet
{

Button submit;

TextField text;

/* A group of radio buttons necessary to only allow one radio button to be selected at the same time.*/

CheckboxGroup radioGroup;

Checkbox male;
Checkbox female;

Checkbox option;

Label name;
public void init()
{

setLayout(null);
submit = new Button("Submit");

text = new TextField("Insert name..",100);

radioGroup = new CheckboxGroup();
male = new Checkbox("Male", radioGroup,true);

female = new Checkbox("Female", radioGroup,false);

option = new Checkbox("Option",false);

name = new Label("Name : ");

submit.setBounds(100,200,100,30);
text.setBounds(20,50,150,25);
male.setBounds(20,120,100,30);
female.setBounds(120,120,100,30);
option.setBounds(20,160,100,30);
name.setBounds(20, 15, 50, 50);
// now that all is set we can add these components to the applet.

add(submit);
add(text);
add(male);
add(female);
add(option);
add(name1);
}
}



Displaying the Image in the Applet
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you use the drawImage() method found in the java.awt.Graphics class.


Program:

import java.applet.*;
import java.net.*;
import java.awt.*;
public class ImageTest extends Applet
{
String str;
Image img;
public void init()
{
img=getImage(getDocumentBase(),"kids.jpg");
}
public void paint(Graphics g)
{
g.drawString("Image is Displayed",10,10);
g.drawImage(img,25,25,300,300,this);
}
}


Or


/*
<applet code="AppletImage.class" width=500 height=500 >
</applet>
*/

public class AppletImage  extends Applet
{
  Image img;
  MediaTracker tr;
  public void paint(Graphics g
{
  tr = new MediaTracker(this);
  img = getImage(getCodeBase()"kids.gif");
  tr.addImage(img,0);
  g.drawImage(img, 00this);
  
}




Write an applet for each of following graphics methods.
drawoval() , drawrect() , drawline() , filloval()


Program:

import java.applet.*;
import java.awt.*;
public class Geometric extends Applet
{
 public void paint(Graphics g)
 {   
g.setColor(Color.GREEN);    g.drawLine(20,20,100,20);    g.drawRect(20,50,90,90);    g.fillRoundRect(130,50,120,70,15,15);    g.setColor(Color.RED);    g.drawOval(20,160,160,100);    g.fillOval(180,160,160,100);  
}
}

/*
<applet code="Geometric.class" width =300  height=300>
   </applet>
*/


Write an applet program that accepts two input string using <param> tag and
concatenate the strings and display it in status window.


Program:

import java.applet.*;
importjava.awt.*;
/*<applet code = AppletProgram.class height = 400 width = 400>
<param name = "string1" value = "Hello">
<param name = "string2" value = "Applet">
</applet>*/
public class AppletProgram extends Applet
{
String str1;
public void init()
{
str1=getParameter("string1").concat(getParameter("string2"));
}
public void paint(Graphics g)
{
showStatus(str1);
}
}


Write a program to design an applet to display three circles filled with three
different colors on screen.


Program:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet

{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
/*
<applet code= MyApplet width= 300 height=300>
</applet>
*/



Write syntax and example of following Graphics class methods
Or

Explain the following methods of applet class:
(i) drawRect()
(ii) drawPolygon()
(iii) drawArc()
(iv) drawRoundRect()
v)drawOval()

(i) drawRect():
The drawRect() method displays an outlined rectangle.
Syntax: void drawRect(inttop, intleft, intwidth, int height)
The upper-left corner of the Rectangle is at top and left.
The dimension of the Rectangle is specified by width and height. 


Example:
g.drawRect(10,10,60,50);


(ii) drawPolygon():
drawPolygon() method is used to draw arbitrarily shaped figures.
Syntax: void drawPolygon(int x[], int y[], intnumPoints)
The polygon’s end points are specified by the co-ordinates pairs
contained within the x and y arrays. The number of points define by
x and y is specified by numPoints.


Example:
intxpoints[]={30,200,30,200,30};
intypoints[]={30,30,200,200,30};
intnum=5;
g.drawPolygon(xpoints,ypoints,num);


(iii) drawArc( ):
It is used to draw arc .
Syntax: void drawArc(int x, int y, int w, int h, intstart_angle,
intsweep_angle);
where x, y starting point, w & h are width and height of arc, and
start_angle is starting angle of arc sweep_angle is degree around the
arc.


Example:

g.drawArc(10, 10, 30, 40, 40, 90);


(iv)drawRoundRect():
It is used to draw rectangle with rounded corners.
Syntax : drawRoundRect(int x,int y,int width,int height,int
arcWidth,int arcHeight)
Where x and y are the starting coordinates, with width and height
as the width and height of rectangle.
arcWidth and arcHeight defines by what angle the corners of rectangle are rounded.


Example: g.drawRoundRect(25, 50, 100, 100, 25, 50);


v).drawOval( )
Drawing Ellipses and circles:
To draw an Ellipses or circles used drawOval() method can be used.
Syntax: void drawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by
top and left and whose width and height are specified by width and height to draw a circle or filled circle, specify the same width and height the following program draws several ellipses and circle.


Example:
g.drawOval(10,10,50,50);


Security Issues with the Applet :

Java applet is run inside a web browser. But an applet is restricted in some areas, until it has been deemed trustworthy by the end user. The security restriction is provided for protecting the user by malicious code, like copy important information from the hard disk or deleting the files. Generally, applets are loaded from the Internet and they are prevented from: the writing and reading the files on client side.

Some security issues to applet are following :
Applets are loaded over the internet and they are prevented to make open network connection to any computer, except for the host, which provided the .class file. Because the html page come from the host or the host specified codebase parameter in the applet tag, with codebase taking precedence.
  
They are also prevented from starting other programs on the client. That means any applet, which you visited, cannot start any rogue process on you computer. In UNIX, applets cannot start any exec or fork processes. Applets are not allowed to invoke any program to list the contents of your file system that means it cant invoke System.exit() function to terminate you web browser. And they are not allowed to manipulate the threads outside the applets own thread group.
  
Applets are loaded over the net. A web browser uses only one class loader that?s established at start up. Then the system class loader can not be overloaded, overridden, extended, replaced.

Applet is not allowed to create the reference of their own class loader. 
 
They cant load the libraries or define the native method calls. But if it can define native method calls then that would give the applet direct access to underlying computer.


Topics covered in this post:
Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of
an applet, passing parameters to applets, applet security issues. 
 

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Java Database Connectivity (JDBC) ,Steps to connect to the database in Java