0% found this document useful (0 votes)
17 views41 pages

Applet

Uploaded by

ritikaghosh0402
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)
17 views41 pages

Applet

Uploaded by

ritikaghosh0402
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/ 41

TECHNIQUE POLYTECHNIC INSTITUTE,

HOOGHLY
LEARNING MATERIALS
Department : Computer Science & Technology Semester : FIFTH(5th )

Subject : JAVA PROGRAMMING

UNIT : (5)Java Applets and Graphics Programming Course Code : CST/5/502Contact Periods : 06 Hrs
Teacher : Debasish Hati Date : ____________________

[Instructions : At the end of this lesson, teacher is asked to give MCQ / Short type questions / Broad type
Questions related to this Unit]
Learning objectives: After completing this topic, the students will be able to:
ILO-5.1.1: Examine web based application using Applet.(AN/PK)
ILO-5.2.1: Classify different graph using applet. (AN/PK)
ILO-5.2.2: Examine Lines and rectangle, Circle.(AN/PK)
_________________________________________________________________________
Content:
5.1 Applet Programming Local and remote applets, How applet differ from application, Preparing to write applets, Building applet code, Applet
life cycle,Creating an Executable Applet, Designing a Web page, Applet tag,Adding Applet to HTML file, Running the Applet,
Passing parameter to applet

5.2 Graphics Programming The Graphics Class, Lines and rectangle, Circle and Ellipse, DrawingArcs, Drawing Polygons, Line Graphs, Using
control loops in Applets,Drawing Bar charts

Introduction
An Applet is the special type of Java program that is run on web browser. The Applet class
provides the standard interface between applet and browser.

An applet class does not have main method and it extends the java.applet.Applet class.
An applet program runs through applet viewer.

Advantages of Applets

Applets are supported by most web browser.


Applets have very less response time, because it works at client side.
Applets are quite secure because of their access of resources.
An untrusted applet has no access to local machine.
The size of applets is small, making it easier to transfer over network.

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Limitations of Applets

Applets require a Java plug-in to execute.


Applets do not support file system.
Applet itself cannot run or modify any application on the local system.
It cannot work with native methods of system.
An applet cannot access the client-side resources.

Applet Life Cycle


It is derived from the Applet class. When an Applet is created, it goes through different
stages; it is known as applet life cycle.

1. Born or initialization state


2. Running state
3. Stopped state
4. Destroyed state
5. Display state

Applet Life Cycle Methods


1. init ( )
The init( ) method is responsible for applet initialization when it is loaded. It is called by
browser or applet viewer only once.

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Syntax

public void init( )


{
//actions
}

2. start ( )
It is invoked after the initialization state and applet entered into running state. It starts
the execution of Applet and the applet becomes an active state.
Syntax

public void start()


{
//actions
}

3. paint( )
This method is used to display output on screen. It takes java.awt.Graphics object as a
parameter. It helps to create Applet GUI such as a colored background, drawing etc.
Syntax

public void paint(Graphics g )


{
//Display statement
}

4. stop( )
This method is responsible to stop the execution and applet becomes temporarily inactive
state. It is invoked when Applet is stopped.
Syntax

public void stop( )


{
//actions
}

5. destroy( )
It destroys and removes the applet from the memory. It is invoked only once. This is end
of the life cycle of applet and it becomes dead.

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Syntax

public void destroy()


{
//actions
}

Developing an Applet Program


Steps to develop an applet program
1. Create an applet (java) code i.e. .java file.
2. Compile to generate .class file.
3. Design a HTML file with <APPLET> tag.

Running the Applet Program


There are two ways to run the applet program
1. By HTML
2. Appletviewer tool
Example : Getting a message printed through Applet

import java.awt.*;
import java.applet.*;
public class AppletDemo
{
public void paint(Graphics g)
{
g.drawString("Welcome to TutorialRide", 50, 50);
}
}

1. Save the above program: AppletDemo.java


2. Compile: > javac AppletDemo.java

//AppletDemo.html

<html>
<head>
<title> AppletDemo </title>
</head>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


<body>
<applet code="AppletDemo.class" width="200" height="250">
</applet>
</body>
</html>

Run the complete program:


> appletviewer AppletDemo.html

NOTE: To execute the applet program through appletviewer tool, write it on command
prompt.
C :\> javac AppletDemo.java
C :\> appletviewer AppletDemo.java

Difference between Applications and Applets

Applications Applets
An application runs stand-alone. An applet program runs under the control of browser.
It can access any data or software available on the It cannot access anything on the system except browser’s
system. service.
Execution start from the init() method because main() is not
Execution start from the main() method.
available.
It can read and write to the file system. Cannot read and write to the file systems.
Does not provide any security. An applet provides the security features.
Application run using Java interpreter. It runs using applet viewer or on web browser.

Parameter in Applet

User-define Parameter can be applied in applet using <PARAM…


> tags. Each <PARAM…> tag has a name and value attribute.

Example:

name = color

Value = red

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Copy

Syntax:

<PARAM name = ……… Value = “………” >

Copy
In an applet code, applet can refer to a parameter by its name and
then find its value.
The two most important thing to handle and set up the parameter is
the <PARAM> tag in the HTML document and an applet code to
parse this parameter.
init() method is used to get hold of the parameters which is defined
in the <PARAM> tags. And getParameter() method is used for
getting the parameters.
In Applet, Parameters are passed on applet when it is loaded.

Example:

param.java

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


import java.applet.*;

import java.awt.*;

public class param extends Applet

String str;

public void init()

str=getParameter("pname");

if (str == null)

str = "Welcome to studytonight.com";

str = "Hello " + str;

public void paint(Graphics g)

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


{

g.drawString(str, 200, 200);

Copy
param.html

<html>

<applet code=param.class height=300 width=300>

<param Name="pname" value="Welcome to


studytonight.com">

</applet>

</html>

Copy

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


How to run an Applet Program

An Applet program is compiled in the same way as you have


been compiling your console programs. However there are
two ways to run an applet.
Executing the Applet within Java-compatible web
browser.

Using an Applet viewer, such as the standard tool,


applet viewer. An applet viewer executes your applet in
a window

For executing an Applet in an web browser, create


short HTML file in the same directory. Inside body tag of the

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


file, include the following code. (applet tag loads the Applet
class)

< applet code = "MyApplet" width=400 height=400 >

< /applet >

Run the HTML file

Running Applet using Applet Viewer

To execute an Applet with an applet viewer, write short HTML


file as discussed above. If you name it as run.htm, then the
following command will run your applet program.

f:/>appletviewer run.htm

Copy

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Graphics in Applet

In Applet, java.awt.Graphicsclass provides methods for using


graphics.
Below are the Methods of the Graphics class.
Sr No. Methods Description
1 public abstract void drawString(String str, int x, int y) Used to draw specified string.
Used to draw a rectangle of specified
2 public void drawRect(int x, int y, int width, int height)
width and height.
Used to draw a rectangle with a
3 public abstract void fillRect(int x, int y, int width, int height) default colourof specified width and
height.
public abstract void drawOval(int x, int y, int width, int Used to draw oval of specified width
4
height) and height.
Used to draw oval with a default
5 public abstract void fillOval(int x, int y, int width, int height)
colour of specified width and height.
Used for drawing lines between the
6 public abstract void drawLine(int x1, int y1, int x2, int y2)
point (x1, x1) and (x2, y2).
public abstract booleandrawImage(Image img, int x, int y,
7 Used for drawing a specified image.
ImageObserver observer)
public abstract void drawArc(int x, int y, int width, int
8 Used for drawing a circular arc.
height, intstartAngle, intarcAngle)
public abstract void fillArc(int x, int y, int width, int height,
9 Used for filling circular arc.
intstartAngle, intarcAngle)
10 public abstract void setColor(Color c) Used to set a colour to the object.

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


11 public abstract void setFont(Font font) Used to set font.

Example:

GraphicsDemo1.java

import java.applet.Applet;

import java.awt.*;

public class GraphicsDemo1 extends Applet

public void paint(Graphics g)

g.setColor(Color.black);

g.drawString("Welcome to studytonight",50, 50);

g.setColor(Color.blue);

g.fillOval(170,200,30,30);

g.drawArc(90,150,30,30,30,270);

g.fillArc(270,150,30,30,0,180);

g.drawLine(21,31,20,300);

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


g.drawRect(70,100,30,30);

g.fillRect(170,100,30,30);

g.drawOval(70,200,30,30);

GraphicsDemo1.html

<html>

<body>

<applet code="GraphicsDemo1.class" width="300"


height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Working with Images in Applet

In Applet programs, images also can be used


java.awt.Image class is used for representing an image.
java.applet, java.awt and java.awt.image are the
packages which are used for event handling.

Loading an image

In Applet, images are loaded using getImage() method. This


method works when the constructor of the Applet is called. It
is always suggested to call the constructor in init() method.
Here are some examples:
Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST
Image image1 = getImage(getCodeBase(),
"image1.gif"); Image image2 =
getImage(getDocumentBase(), "image1.jpeg"); Image image3
= getImage(new
URL("http://java.sun.com/graphics/image.gif"));

Displaying an image

In Applet, images are displayed using drawImage() method.


This method is supplied by the Graphics object, which is
passed to paint() method.

Example:

Aimage.java

import java.awt.*;

import java.applet.*;

public class Aimage extends Applet

Image img1;

public void init()

img1=getImage(getDocumentBase(),"icon.png");

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


public void paint(Graphics g)

g.drawImage(img1,100,100,this);

Aimage.html

<html>

<applet code=Aimage height=300 width=300>

</applet>

</html>

Copy

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


EventHandling in Applet

In Applet we can also perform event handling.

Below is an example of event handling which prints a


message when clicked on the button.

Example:

EventAppletDemo.java

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


public class EventAppletDemo extends Applet
implements ActionListener

Button b1;

TextField tf1;

public void init()

tf1=new TextField();

tf1.setBounds(30,40,200,20);

b1=new Button("Click");

b1.setBounds(80,150,60,50);

add(b1);

add(tf1);

b1.addActionListener(this);

setLayout(null);

public void actionPerformed(ActionEvent e)

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


{

tf1.setText("Welcome to studytonight");

Myapplet.html

<html>

<body>

<applet code="EventAppletDemo.class" width="300"


height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Animation in Applet

In Applet, we can also create animations in a program using a


gif image. Below is an example in which drawImage() method
is used which is of Graphics class, it is used for displaying an
image.
Note: Download a gif file for the below example

Example:

AnimationDemo.java
Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST
import java.awt.*;

import java.applet.*;

public class AnimationDemo extends Applet

Image p;

public void init()

p = getImage(getDocumentBase(),"ball.gif");

public void paint(Graphics g)

for(inti=0;i<500;i++)

g.drawImage(p, i,50, this);

try

{
Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST
Thread.sleep(100);

catch(Exception e)

{}

AnimationDemo.html

<html>

<body>

<applet code="AnimationDemo.class" width="300"


height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


JApplet class

In Java, JApplet is the public class of swing. JApplet extends


the class in java.applet.Applet. JApplet generates a bytecode
with the help of JVM or the Applet viewer. JApplet can be
written in any programming language and then can be
compiled for Java Byte code.

Example:

JAppletDemo.java

import java.applet.*;

import javax.swing.*;
Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST
import java.awt.event.*;

public class JAppletDemo extends JApplet implements


ActionListener

JButton b;

JTextField t;

public void init()

t=new JTextField();

t.setBounds(30,40,220,20);

b=new JButton("Click");

b.setBounds(80,150,70,40);

add(b);

add(t);

b.addActionListener(this);

setLayout(null);

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


public void actionPerformed(ActionEvent e)

t.setText("Welcome to studytonight.com");

JAppletDemo.html

<html>

<body>

<applet code="JAppletDemo.class" width="300"


height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Painting in Applet

Below is an example of Painting using mouseDragged()


method of MouseMotionListener in Applet.

Example:

PaintingDemo.java

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


public class PaintingDemo extends Applet implements
MouseMotionListener

public void init()

addMouseMotionListener(this);

setBackground(Color.white);

public void mouseDragged(MouseEvent me)

Graphics g=getGraphics();

g.setColor(Color.black);

g.fillOval(me.getX(),me.getY(),5,5);

public void mouseMoved(MouseEvent me)

{}

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


PaintingDemo.html

<html>

<body>

<applet code="PaintingDemo.class" width="300"


height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Analog Clock in Applet

In java, Applet can be used for creating anAnalog Clock. For


creating a program for the Analog clock, java.apple,
java.awt, java.util, and java.text package are imported.
Date and Time functions are also used. Math functions play
an important role in creating an Analog Clock. below is a
program for creating anAnalog Clock.

Example:

AnalogDemo1.java

import java.applet.*;

import java.awt.*;

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


import java.util.*;

import java.text.*;

public class AnalogDemo1 extends Applet implements


Runnable

int width, height;

Thread t = null;

booleanthreadSuspended;

int hours=0, minutes=0, seconds=0;

String timeString = "";

public void init()

width = getSize().width;

height = getSize().height;

setBackground( Color.black );

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


public void start()

if ( t == null )

t = new Thread( this );

t.setPriority( Thread.MIN_PRIORITY );

threadSuspended = false;

t.start();

else

if ( threadSuspended )

threadSuspended = false;

synchronized( this )

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


notify();

public void stop()

threadSuspended = true;

public void run() {

try {

while (true) {

Calendar cal = Calendar.getInstance();

hours = cal.get( Calendar.HOUR_OF_DAY );

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


if ( hours> 12 ) hours -= 12;

minutes = cal.get( Calendar.MINUTE );

seconds = cal.get( Calendar.SECOND );

SimpleDateFormat formatter = new


SimpleDateFormat( "hh:mm:ss",
Locale.getDefault() );

Date date = cal.getTime();

timeString = formatter.format( date );

if ( threadSuspended ) {

synchronized( this ) {

while ( threadSuspended ) {

wait();

repaint();

t.sleep( 1000 );

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


}

catch (Exception e) { }

void drawHand( double angle, int radius, Graphics g


) {

angle -= 0.5 * Math.PI;

int x = (int)( radius*Math.cos(angle) );

int y = (int)( radius*Math.sin(angle) );

g.drawLine( width/2, height/2, width/2 + x,


height/2 + y );

void drawWedge( double angle, int radius, Graphics


g ) {

angle -= 0.5 * Math.PI;

int x = (int)( radius*Math.cos(angle) );

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


int y = (int)( radius*Math.sin(angle) );

angle += 2*Math.PI/3;

int x2 = (int)( 5*Math.cos(angle) );

int y2 = (int)( 5*Math.sin(angle) );

angle += 2*Math.PI/3;

int x3 = (int)( 5*Math.cos(angle) );

int y3 = (int)( 5*Math.sin(angle) );

g.drawLine( width/2+x2, height/2+y2, width/2 + x,


height/2 + y );

g.drawLine( width/2+x3, height/2+y3, width/2 + x,


height/2 + y );

g.drawLine( width/2+x2, height/2+y2, width/2 + x3,


height/2 + y3 );

public void paint( Graphics g ) {

g.setColor( Color.pink );

drawWedge( 2*Math.PI * hours / 12, width/5, g );

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


drawWedge( 2*Math.PI * minutes / 60, width/3, g );

drawHand( 2*Math.PI * seconds / 60, width/2, g );

g.setColor( Color.white );

g.drawString( timeString, 10, height-10 );

Copy
AnalogueDemo1.html

<html>

<body>

<applet code="AnalogDemo1.class" width="300"


height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


Copy

Digital Clock in Applet

In java, Applet can be used for creating a Digital Clock. For


creating a program for the digital clock, java.apple,
java.awt, java.util, and java.text package are imported.
Date and Time functions are also used. below is a program for
creating a Digital Clock.

Example:

DigitalClockDemo1.java

import java.applet.*;

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


import java.awt.*;

import java.util.*;

import java.text.*;

public class DigitalClockDemo1 extends Applet


implements Runnable

Thread t = null;

int h=0, m=0, s=0;

String timeString = "";

public void init()

setBackground( Color.black);

public void start()

t = new Thread( this );

t.start();

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


}

public void run()

try

while (true)

Calendar cal = Calendar.getInstance();

h = cal.get( Calendar.HOUR_OF_DAY );

if ( h> 12 ) h -= 12;

m = cal.get( Calendar.MINUTE );

s = cal.get( Calendar.SECOND );

SimpleDateFormat f = new
SimpleDateFormat("hh:mm:ss");

Date date = cal.getTime();

timeString = f.format( date );

repaint();

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


t.sleep( 1000 );

catch (Exception e) { }

public void paint( Graphics g )

g.setColor( Color.white );

g.drawString( timeString, 50, 50 );

Copy
DigitalClockDemo1.html

<html>

<body>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST


<applet code="DigitalClockDemo1.class" width="300"
height="300">

</applet>

</body>

</html>

Java Programming | UNIT-5 | Prepared By: Debasish Hati, Incharge, DCST

You might also like