Unit1
Unit1
Applet tag
Introduction
• Java supports two types of programming :
1) Application program:
Application is a program that runs on your computer under the operating system of that
Computer.
2) Applet program:
An applet is an application designed to be transmitted over the Internet and executed
by a Java-compatible Web browser.
Applet concept
Applet is small programs that are primarily used in internet computing, they can be
transported over the internet from one computer to another and run using applet viewer
or java compatible web browser.
Java applet is a java class that you embed in an HTML page and is downloaded
and executed by a web browser.
Applet can’t be executed directly.
For running an applet, HTML file must be created which tells the browser what to
load and how to run it.
applet begins execution via loading of a HTML page “containing it” after that java
enabled web browser or “applet viewer” is required to run an applet
Now, Web pages not only contain static text or simple image but it can also perform
arithmetic operation, displays graphics, play sounds and moving Images.
We can embed applets into web pages in two ways:
1.We can write our own applets and embed them into web pages.
2.We can download an applet from a remote computer system and then embed it into
a web page.
Types of applet:
1) Local Applet
An applet developed locally and stored in a local system is known as local applet.
When a web page is trying to find a local applet, it does not need to use the Internet
and therefore the local system does not require the Internet Connection.
It simply searches the directories in the local system and locates and loads the
specified applet.
User can write his own applets and embed them into web pages.
2) Remote Applet
Limitations of applet
All the restriction and limitations are placed in the interest of security of systems. These
ensure that an applet cannot do any damage to local system.
Applets allow neither to execute any application nor to load any DLL s on the local
system.
Applets do not need a main method.
Applet runs under an applet viewer or a java compatible web browser.
Applets can’t read or write files on the web user’s disk. If information must be saved to
disk as an applet is executing, the storage of information must be done on the disk from
which the web page is served.
Applet cannot make network connection to a computer other than the one from which
the web page is served, expect to direct the browser to a new location.
Applets are restricted from using libraries from other languages such as C,C++.
Applet cannot run any programs on the web user’s system, including browser plug-ins,
activeX controls or other browser related items.
Some of Java’s functionality (like removal of pointers, verification of byte code and
restricted remote and local file access) blocked for applets because of security
concerns.
Applet class contains 21 methods that are used to display images, play audio files,
respond to events and obtain information about applet’s execution environment,
referred as applet’s context.
No Methods Action
1 Image getImage(URL url): Used to retrieve an Image identified by
URL
2 AudioClip getAudioClip(URL url) Used to retrieve Audioclip object that is
identified by URL.
Void play(URL url): If an audioThe play method is used to
3
play an audio clip
Stub:
A stub is a small piece of code that provides the linkage between your applet and
the web browser.
AppletContext Interface
It defines methods that allow an applet to access the context in which it is being run.
AppletContext interface is accessed using getAppletContext() method of Applet class.
It provides 7 methods that allows an applet to obtain information about and manipulate
its environment.
1. Enumeration getApplets()
Government Polytechnic, Ahmedabad Page 1
Advance Java Programming (3360701) Unit-1 Java applet
Color class:
we can fill colors in applet using Color class of awt package.
Pre-defined colour in java:
Color.black Color.blue Color.cyan Color.mangenta
Color.pink
For example this sets background color to green and text color to red:
setBackground(Color.green); or
setForeground(Color.red); or
setColor(Color.red);
Color constructor:
We can create any new color bu using constructor of Color class.
It takes three integer parameters and uses RGB combination for creating
new colors.
Color colorobj=new Color (int red ,int green, int blue );
E.g: Color c=new Color(255,100,100);
g.setColor( c );
1) Initialization state
• Applet enters the initialization state when it is first loaded.this is achieved by calling
the init() method of Applet class.The applet is born.
• Initialization occurs only once in the applet’s life cycle.
• We do following at this stage,
- create objects needed by the applet
- set up initial values,initailize variables
- Load images or fonts
- set up colors
• To provide any of behaviour mentioned above,we must overrride init() method:
public void init()
{
............(Action)
............
}
2) Running state
• Applet enters the running state when the system calls start() method of Applet
class.
• This occurs automatically after applet is initialized.
• Starting of applet can also occur if the applet is already in “stopped” (idle) state.
• Unlike init() method,the start() method may be called more than once.
• We may override the start() method to create a thread to control the applet.
public void start( )
{
............(Action)
............
}
3) Idle or stopped state
• An applet becomes idle when it is stoppped from running.
• Stopping occurs automatically when we leave the page containing the currently
running applet.
• We can also stop applet by calling the stop() method explicitly.
• If we use thread to run the applet then we must use stop() method to terminate the
thread.
• To do this override stop() method:
public void stop()
{
..................(Action)
..................
}
4) Dead state
5) Display state
• Applets moves to the display state ,whenever it has to perform some output
operations on the screen.
• This happens immidiately after the applet enters into the running state.
• The paint() method is called to accomplish this task.
• Almost every applet will have paint() method .deault version of paint() method
does nothing.
• We must have to override paint() if we want anything to be displayed on the screen.
• Display state is not considered as a part of the applet’s life cycle.
• The paint() method is defined in the applet class.it is inherited from the
Component class ,a super class of Applet.
Applet code uses the services of two classes,namely Applet and Graphics from java
class.
Applet class is contained in java.applet package ,which provides life and behaviour
to the applet through its methods such as init() ,start() and paint().
Applet class maintains the life cycle of an applet.
When an applet is loaded ,java automatically calls a series of Applet class methods for
the starting,running,stopping the applet code.
When paint() method is called ,it will actually display the result of the applet code on
the screen.The output may be text,graphics or sound.
The paint() method requires a Graphics object as an argument.
Output:
Java programs resides on web pages.to run a java applet ,it is necessary to have a web
page that reference thta applet.
A web page is made up of text and HTML tags that can be interpreted by a web
browser or appletviewer.
A web page is also known as HTML page or HTML document.
Web pages are stored using a file extension .html
HTML files should be stored in the same directory as the compiled code of the
applets.
Web page is divided in to three major sections:
1) Comment section(optional) 2) Head Section(optional) 3) Body section
Head section:
<HEAD>
<TITLE> Welcome to Java Applets </TITLE>
</HEAD>
Here,text enclosed in <TITLE> and </TITLe> will apper in the title bar of the web
browser when it displays the page.
Body Section:
After Head section comes the body section.this section contains the entire information
about the web page and its behaviour.
<BODY>
<CENTER>
<H1> WELCOME </H1>
</CENTER>
<APPLET .......>
</APPLET>
</BODY>
HTML tags
• <HTML>...........</HTML>
• <HEAD>...........</HEAD>
• <TITLE>...........</TITLE>
• <BODY>...........</BODY>
• <H1>........</H1>.......<H6>..........</H6>
• <CENTER>...........</CENTER>
• <APPLET...>
• <APPLET...>...........</APPLET>
• <PARAM....>
• <B>..........</B>
• <BR>
• <P>
• <IMG..........>
• <HR>
• <A.....></A>
• <FONT>..........</FONT>
• <!....................> (comment line)
• The ellipsis in the tag <APPLET ....> indicates that it contains certain attributes that
must be specified.
</APPLET>
This HMTL code tells the browser to load the compiled java applet
Hellojava.class ,which is in the same directory as this HTML file .and also specify display
area for the applet output.
<HTML>
<! This page includes a welcome title in title bar and also display a welcome message. >
<HEAD>
<TITLE> Welcome to Java Applets </TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> WELCOME </H1>
</CENTER>
<APPLET CODE=Hellojava.class WIDTH=200 HEIGHT=400 >
</APPLET>
</BODY>
</HTML>
6. Running an applet
Appplet tag
• <APPLET ....> tag supplies the name of applet to be loaded and tells the browser
how much space the applet requires.
• The ellipsis in the tag <APPLET ....> indicates that it contains certain attributes that
must be specified.
</APPLET>
This HMTL code tells the browser to load the compiled java applet
Hellojava.class ,which is in the same directory as this HTML file .and also specify display
area for the applet output.
[CODEBASE= codebase_URL]
CODE=AppletfileName.class
[ALT = Alternate_text ]
[Name = applet_instance_name ]
WIDTH = Pixels
HEIGHT = Pixels
[ ALIGN= Alignment]
[ VSPACE = Pixels ]
[ HSPACE = Pixles]
>
[ <PARAM NAME=name1 VALUE= value1 >]
[ <PARAM NAME=name2 VALUE= value2 >]
..............
</APPLET>
Everything in [ ] indicates the option can be used when integrating an applet into a
webpage.
Attributes of Applet tag:
NO Attribute Meaning
Specifies the name of the applet class to be
loaded.
1 CODE=AppletfileName.class It is the name of already compiled .class file in
(necessary)
which the executable java byte code for the applet is
stored.
CODEBASE= codebase_URL Specifies URL of the directory in which the applet
2 (Optional) resides.(must used in remote applet)
Specify width and height of the space on the
3 WIDTH = Pixels
HTML page that will be reserved for applet.
HEIGHT = Pixels(necessary)
A name for the other applet on the page may refer
Name = applet_instance_name
4 to this applet. This facilitates inter applet
(Optional)
communication.
Alignment of applet on page:
[ ALIGN= Alignment] Values for alignment are:
5
(Optional)
(TOP, BOTTOM, LEFT, RIGHT,
MIDDLE,ABSMIDDLE,ABSBOTTOM,
TEXTTOP,BASELINE )
[ VSPACE = Pixels ] It specifies amount of vertical blank space the
(Optional) browser should leave surrounding the applet.
6
it is Used only when ALIGN some vertical
alignment is specified with the ALIGN attribute
It is Used only when ALIGN is set to LEFT or
[ HSPACE = Pixels] RIGHT, It specifies amount of horizontal blank
7 (Optional)
space the browser should leave surrounding the
applet.
[ALT = Alternate_text ] Non _java browser will display this text where the
8 (Optional) applet would normally go.
import java.applet.*;
import java.awt.*;
public class Helloparam extends Applet
{
String str;
public void init()
{
str=getParameter("string");
if(str==null)
str="java";
str="hello" + str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
Output:
• Example:
import java.awt.*;
import java.applet.*;
/*<applet code=NumValues.class height=400 width=400>
</applet> */
public class NumValues extends Applet
{
public void paint(Graphics g)
{
int val1=10;
int val2=20;
int sum= val1 + val2;
String s = "sum :" + String.valueOf(sum);
g.drawString(s,10,100);
}
}
Write an applet program which takes two input values from user and
calculate sum of two values.
/* <html><body>
<applet code=UserIn.class width=400 height=400> </applet>
</body> </html>
*/
import java.awt.*;
import java.applet.*;
public class UserIn extends Applet
{
TextField text1,text2;
public void init()
{
text1 = new TextField(8); //creates Textfield (text box) object
text2 = new TextField(8);
add (text1); //add textField to our applet
add (text2);
text1.setText("0"); //set default value “0” in TextFeield
text2.setText("0");
}
public void paint(Graphics g)
{
int x=0,y=0,z=0;
String s1,s2,s;
g.drawString("Input number in both textbox ",10,50);
try
{
s1=text1.getText(); //to get String object from TextField
x=Integer.parseInt(s1); //convert String object to integer value
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception e) { }
z = x + y;
s=String.valueOf(z); //converts integer sum into String objecttype
g.drawString("the sum is :" ,10,75);
g.drawString(s,100,75);
}
public boolean action(Event event ,Object obj)
Government Polytechnic, Ahmedabad Page 1
Advance Java Programming (3360701) Unit-1 Java applet
{
repaint();
return true;
}
}
Painting an applet
(Update, paint, repaint method)
• All three methods are defined in Component class.
3) update() method:
• The system does not actually call the paint() method,actually update() called
directly by the system.
• The built in update procedure first fills in the entire component with a
background color.
• then it calls the paint() method ,the paint() method draws on a rectanglar area that
has already been filled with the background color.
• update() method controls what happens when repaint is called;this method can be
overriden.
• update() method improves drawing performance along with paint method.
• update() method clears the current display and calls the paint() method.
• Syntax:
public void update( Graphics g)
{
paint ( g) ;
}
import java.awt.*;
import java.applet.*;
/*<applet code=PaintMethod.class width=200 height=400>
</applet>*/
}
}
catch(InterruptedException e)
{
}
}
public void update(Graphics g)
{
paint(g);
}
{
g.drawString( "Hello world ! ",100,counter);
}
else
{
g.drawString( "Hello java ! ",10,counter);
}
}
}
Graphics class
The Graphics class is part of AWT.
Graphics class is contained in java.awt.Graphics and it includes methods for
drawing types of shapes or text in variety of fonts.
Every applet has its own area of the screen known as canvas. where it creates its
display.
A Java applet draws graphical images inside its space using the coordinate system.
Java’s coordinate system has the origin (0, 0) in the upper-left corner.
Positive x values are to the right and positive y values are to the bottom. The values
of coordinates x and y are in pixels.
Using drawing methods of class we can draw a shape on the screen.
All the drawing methods have arguments representing end points, corners or starting
location of shape as values in applet’s coordinate system.
Canvas
Syntax: g.copyArea (int x, int y, int width, int height, int new_x, int new_y)
g.drawRoundRect (int x, int y, int width, int height, int width, int height)
Width
Height & width of
corner
height
Width
Height & width of
corner
height
• An arc is a part of an oval. We can say oval is an series of arcs that are connected
together in an orderly manner.
• drawArc () is designed to draw arc which has six parameter. In which last two
presents starting angle of the arc and the number of degrees (sweep angle) around the
arc.
• Java considers the three O’clock as zero degree position and degree increases in
anticlockwise direction.(see fig(a))
• We can draw in backward direction by specifying
E.g : If last argument is -135° and starting angle is 45° then arc is as in fig.(b)
Arc angle
Start angle
Draws a polygon:
• Polygons are shape with many sides. It is a set of lines connected together.
• Te end of the first line is the beginning of another line,the end of second line is the
beginning of third and so on.
• We can draw polygon using drawLine( ) ,drawPolygon() and fillPolygon()
method.
{
int x[]={20,120,220,20};
int y[]={20,120,20,20};
int n= x. length;
Polygon poly=new Polygon(x , y , n);
g.setColor(Color.pink);
g.fillPolygon(poly);
g.setColor(Color.black);
poly.addPoint(120,120);
poly.addPoint(320,320);
poly.addPoint(220,120);
poly.addPoint(120,120);
g.drawPolygon(poly);
}
}
Example1:
Write a an applet which takes three input from user and finds bigger out of them.
/*<applet code=UserIn1.class width=400 height=600>
</applet>*/
import java.awt.*;
import java.applet.*;
public class UserIn1 extends Applet
{
TextField text1,text2,text3;
try
{
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
s3=text3.getText();
z=Integer.parseInt(s3);
}
catch(Exception e)
{
}
if(x>y && x>z)
{
s=String.valueOf(x);
g.drawString(s,10,75);
}
else if( y>x && y>z)
{
s=String.valueOf(y);
g.drawString(s,10,75);
}
else
{
s=String.valueOf(z);
g.drawString(s,10,75);
}
}
public boolean action(Event event ,Object obj)
{
repaint();
return true;
}
}
Example-2:
Write a applet program which reverse the string.
import java.awt.*;
import java.applet.*;
/*<applet code =reverse_str.java width=200 height=400>
</applet>*/
public class reverse_str extends Applet
{
String str,s;
public void init()
{
str=getParameter(" ");
if(str==null)
str="java";
str="Hello " + str;
StringBuffer s=new StringBuffer( str);
s=s.reverse();
str=String.valueOf(s);
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
Example :3
Write an applet program which uses Graphics class methods.
import java.awt.*;
import java.applet.*;
/*<applet code=LineRect.class width=400 height=400>
</applet>
*/
public class LineRect extends Applet
{
public void paint(Graphics g)
{
Government Polytechnic, Ahmedabad Page 1
Advance Java Programming (3360701) Unit-1 Java applet
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.clearRect(10,60,10,20);
g.copyArea(10,10,50,50,100,100);
g.fillRect(60,10, 30,80);
g.setColor(Color.red);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,110,60,30,5,5);
g.drawLine(100,10,230,140);
g.drawLine(100,140,230,10);
g.setColor(Color.green);
g.drawOval(260,50,180,180);
g.setColor(Color.black);
g.fillOval(280,100,50,50);
g.fillOval(350,100,50,50);
g.setColor(Color.pink);
g.fillArc(310,160,80,40,180,180);
}
}
Example 4:
Write an applet which draws an national flag.
import java.awt.*;
import java.applet.*;
/*<applet code=Flag1.class width=800 height=500>
</applet>*/
public class Flag1 extends Applet
{
public void paint(Graphics g)
{
g.fillRect(180,70,18,400);
g.setColor(Color.orange);
g.fillRect(200,70,150,40);
g.setColor(Color.white);
g.fillRect(200,120,150,40);
g.setColor(Color.green);
g.fillRect(200,150,150,40);
g.setColor(Color.blue);
g.fillOval(260,110,40,40);
g.setColor(Color.gray);
g.fillRect(90,470,200,20);
g.fillRect(60,490,260,20);
g.drawString("National Flag",100,40);
}
}
Example :5
Write an applet which draws circle ,square and right angle triangle.
import java.awt.*;
import java.applet.*;
/*<applet code=sqr.class width=800 height=800>
</applet>*/
public class sqr extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(180,70,100,100); //draws square
g.drawLine(50,70,50,170);
g.drawLine(50,170,150,170);
g.drawLine(150,170,50,70);
//draws a circle
g.drawOval(200,200,50,50);
g.fillOval(50,200,50,50);
}
Example:
Write an applet program which add two values using <param> tag.
import java.applet.*;
import java.awt.*;
public class Paramsum extends Applet
{
String s1,s2,s;
int a,b,sum;
public void init()
{
s1=getParameter("value1");
s2=getParameter("value2");
a=Integer.parseInt(s1);
b=Integer.parseInt(s2);
}
public void paint(Graphics g)
{
sum=a+b;
s=String.valueOf(sum);
g.drawString(s,10,100);
}
}
/*
<html>
<! parameterized HTML file>
<HEAD>
<TITLE>Welcome to java Applets</TITLE>
</HEAD>
<BODY>
<APPLET CODE=Paramsum.class width=400 height=400 >
<PARAM NAME="value1" VALUE= "10">
<PARAM NAME="value2" VALUE= "20">
</APPLET>
</BODY>
</html>
*/
Question list