Applet Unit II
Applet Unit II
An applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and
hosted on a web server.
Applets are used to make the website more dynamic and entertaining.
Important points :
All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.
In general, execution of an applet does not begin at main() method.
Output of an applet window is not performed by System.out.println(). Rather it is handled with various
AWT methods, such as drawString().
Types of applets
1. Local applet
2. Remote applet
Local applets
Local applets are developed and stored locally, and therefore do not require an Internet connection to
be located because the directory is located on the local system.
Remote applets
Remote applets are stored in a remote computer and an Internet connection is needed to access them.
The remote applet is designed and developed by other developers. To find and load a remote applet,
you need to know the address of the network applet, i.e., the Uniform Resource Locator (URL).
The difference between Application and Applet:
Applications are just like a Java Applets are small Java programs that are
program that can be executed designed to be included with the HTML
Definition
independently without using the web document. They require a Java-enabled
web browser. web browser for execution.
The “javac” command is used to Applet programs are compiled with the
compile application programs, “javac” command and run using either the
Compilation
which are then executed using the “appletviewer” command or the web
“java” command. browser.
Applications can execute the Applets cannot execute programs from the
Execution
programs from the local system. local machine.
Read and Write It supports the reading and writing It does not support the reading and writing
Operation of files on the local computer. of files on the local computer.
Java applications are self- Applet programs cannot run on their own,
Restrictions contained and require no additional necessitating the maximum level of
security because they are trusted. security.
Applet class
The Applet class provides a standard interface between applets and their environment. The Applet
class is the superclass of an applet that is embedded in a Web page or viewed by the Java Applet
Viewer. The Java applet class gives several useful methods to give you complete control over the
running of an Applet. Like initializing and destroying an applet, It also provides ways that load and
display Web Colourful images and methods that load and play audio and Videos Clips and Cinematic
Videos.
Methods Description
void init() The first method to be called when an applet begins its execution.
Called automatically after init() method to start the execution of
void start()
an applet.
void stop() Called when an applet has to pause/stop its execution.
void destoy() Called when an appLet us finally terminated.
String getParameter(String
Returns the value of a parameter defined in an applet
ParameterName)
Returns an Image object that contains an image specified at
Image getImage(URL url)
location, url
void play(URL url Plays an audio clip found at the specified at location, url
Shows a message in the status window of the browser or
showStatus(String str)
appletviewer.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
• init() : init() is the first method to be called. This is where variable are initialized. This method
is called only once during the runtime of applet.
• start() : start() method is called after init(). This method is called to restart an applet after it has
been stopped.
• stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
• destroy() : destroy() method is called when your applet needs to be removed completely from
memory.
Advantages of Applet
It runs inside the browser and works on the Client-side, so it takes less time to respond.
It is more Secured
It can be Executed By multi-platforms with any Browsers, i.e., Windows, Mac Os, Linux Os.
it takes very less response time as it works on the client side.
It can be run on any browser which has JVM running in it.
They increase interactivity for users.
Various small tasks such as performing login, inventory checking, task scheduling can be done by
applets running over Intranets.
Disadvantages of Applet
The applet life cycle can be defined as the process of how the object is created, started, stopped, and
destroyed during the entire execution of its application. It basically has five core methods namely
init(), start(), stop(), paint() and destroy().These methods are invoked by the browser to execute.
There are five methods of an applet life cycle, and they are:
o init(): The init() method is the first method to run that initializes the applet. It can be invoked
only once at the time of initialization. The web browser creates the initialized objects, i.e., the
web browser (after checking the security settings) runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet. It is
invoked immediately after the init() method is invoked. Every time the browser is loaded or
refreshed, the start() method is invoked. It is also invoked whenever the applet is maximized,
restored, or moving from one tab to another in the browser. It is in an inactive state until the
init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is invoked
whenever the applet is stopped, minimized, or moving from one tab to another in the browser,
the stop() method is invoked. When we go back to that page, the start() method is invoked
again.
o destroy(): The destroy() method destroys the applet after its work is done. It is invoked when
the applet window is closed or when the tab containing the webpage is closed. It removes the
applet object from memory and is executed only once. We cannot start the applet once it is
destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw shapes like
circle, square, trapezium, etc., in the applet. It is executed after the start() method and when the
browser or applet windows are resized.
1. init()
2. start()
3. paint()
1. stop()
2. destroy()
Applet Life Cycle Working
o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-side. It
doesn't have the main() method because it runs in the browser. It is thus created to be placed on
an HTML page.
o The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet class. And
thus, we can use all the methods of that class.
These methods are invoked by the browser automatically. There is no need to call them explicitly.
1. /First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
There are two standard ways in which you can run an applet :
7. Executing the applet within a Java-compatible web browser.
8. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer executes
your applet in a window. This is generally the fastest and easiest way to test your applet.
Applets are embedded in HTML documents with the <APPLET> tag. The <APPLET> tag resembles
the HTML <IMG> image tag. It contains attributes that identify the applet to be displayed and,
optionally, give the web browser hints about how it should be displayed.[50] The standard image tag
sizing and alignment attributes, such as height and width, can be used inside the applet tag. However,
unlike images, applets have both an opening <APPLET> and a closing </APPLET> tag. Sandwiched
between these can be any number of <PARAM> tags that contain data to be passed to the applet:
<APPLET attribute
attribute ... >
<PARAM parameter >
<PARAM parameter >
...
</APPLET>
An applet tag contains many attributes that give you a good control over the your applet.
• CODE
This tag is used to specify the name of the your applet's .class file. This is a must required attribute in
an <applet> tag.
In this example, we have defined an applet whose compiled code is found within a file named
"Applet1". This compiled .class file is searched in the same directory which contains Applet1.java file.
The width and height of this applet will be 400 pixels each
• WIDTH
This tag is used to specify the width of our applet window to be displayed within a browser or
appletviewer. This is also a must required attitude in an <applet> tag. Width is specified in pixels.
• HEIGHT
This tag is used to specify the height of our applet window in pixels, This is also a must required
attribute in an <applet> tag.
This tag is used to give a name to an applet class and this name will be used when some other applet wish to
communicate with this applet. This is also an optional attribute in <applet> tag.
In this example, we have defined an applet whose compiled code is found within a file named
"Applet1". The width and height of this applet will be 400 pixels each and we are referring to this
applet by the name "firstApplet", and this name will be used while communication with another
applet.
CODEBASE
This tag is used to specify the directory location containing your applet's .class file.
<applet code ="Applet1" width= 400 height=400 codebase ="http://MyWebsite.com//Folder">
</applet>
In this example, we have defined an applet whose compiled code is found within a file named
"Applet1", which is found at the URL ""http://MyWebsite.com//Folder". This width and height of this
applet will be 400 pixels each.
• PARAM
This is a sub-tag within <applet> tag and it is used to specify the parameters to be passed to an applet.
This tag is an optional attribute within an <applet> tag.
Two attributes within a <param> tag are :
o name : This attribute is used to specify the name of the parameter passed to the applet.
o value : This attribute is used to specify the value of the parameter passed to the applet.
<applet code ="Applet1" width=400 height=400>
In this example, we have defined an applet whose compiled code is found within a file named
"Applet1". This width and height of this applet will be 400 pixels each and we are passing two
parameters to the applet. These parameters are named City and Name and their values are Houston and
Roger.
Parameters specify extra information that can be passed to an applet from the HTML page. Parameters
are specified using the HTML’s param tag.
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value of the
parameter respectively. For example, the param tags for passing name and age parameters looks as
shown below:
Now, these two parameters can be accessed in the applet program using the getParameter() method of
the Applet class.
getParameter() Method
The getParameter() method of the Applet class can be used to retrieve the parameters passed from the
HTML page. The syntax of getParameter() method is as follows:
String getParameter(String param-name)
Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init(){
n = getParameter("name");
a = getParameter("age");}
public void paint(Graphics g){
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);}}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
The line is the simplest shape that we can draw with the Graphics class. The drawLine() method takes
two pairs of coordinates (x1, y1) and (y1, y2) as arguments and draws a line between them. It has the
following syntax:
g.drawLine(x1, y2, x2, y2);
Parameters: The drawLine method takes four arguments:
x1 – It takes the first point’s x coordinate.
y1 – It takes first point’s y coordinate.
x2 – It takes second point’s x coordinate.
y2 – It takes second point’s y coordinate
Example:
• import java.awt.*;
• import java.applet.*;
• public class Line extends Applet
• {
• public void paint(Graphics g)
• {
• g.drawLine(100,10,250, 150);
• g.drawLine(100,150,150,10);
• }
• }
• <html>
• <head>
• </head>
• <body><applet code = "Line.class" width = "420" height = "320"></applet>
• </body>
• </html>
Output:
Draw a Polygon in Java Applet
Polygons are shapes with many sides. It may be considered a set of lines connected. The end of the
first line is the beginning of the second line, the end of the second is the beginning of the third, and so
on. It suggests that we can draw a polygon with n sides using the drawLine() method n times in
succession.
We can draw polygons more conveniently using the drawPolygon() method of Graphics class. This
method takes three arguments:
Example:
• import java.awt.*;
• import java.applet.*;
• public class polygon extends Applet
• {
• int a1[]={20, 120, 220, 20};
• int b1[]={20, 120, 20, 20};
• int n1=4;
• int a2[]= {120, 220, 220, 120};
• int b2[]= {120, 20, 220, 120};
• int n2=4;
• public void paint(Graphics g)
• {
• g.drawPolygon(a1,b1,n1);
• g.fillPolygon(a2,b2,n2);
• }
• }
• <html>
• <head>
• </head>
• <body>
• <applet code = "polygon.class" width = "480" height = "360"></applet>
• </body>
• </html>
Output:
Draw Arc in Applet Window Example
An arc can be drawn using the drawArc () method. This method takes six arguments in which the first
four are same as the arguments of the drawoval () method and the next two represents the starting
angle of the arc and the sweep angle around the arc, respectively.
The general form of the drawArc () method is:
void drawArc (int a1, int b1, int w, int h, int strt_angle, int sweep_angle)
void fillArc (int a1, int b1, int w, int h, int strt_angle, int sweep_angle)
where,
a1, b1 is the coordinate of the top left comer of the bounding rectangle
w is the width of the bounding rectangle
h is the height of the bounding rectangle
strt _angle is the starting angle of the arc (in degrees)
sweep_angle is the number of degrees (angular distance) around the arc (in degrees)
Example:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DrawArc extends Applet {
public static void main(String[] args) {
Frame DrawArcApplet = new Frame("Draw Arc in Applet Window Example");
DrawArcApplet.setSize(350, 250);
Applet DrawArc = new DrawArc();
DrawArcApplet.add(DrawArc);
DrawArcApplet.setVisible(true);
DrawArcApplet.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void paint(Graphics g) {
// draws String
g.drawString("This is Arc Shapes Example", 100, 70);
// Draws an Arc Shape
g.drawArc(30,5, 200, 200, 0, -90); //Syntax For:- drawArc(int xTopLeft, int yTopLeft, int width, int
height, int startAngle, int arcAngle);
// Fill an Arc Shape
g.fillArc(30, 5, 200, 200, 0, -90); //Syntax For:- fillArc(int xTopLeft, int yTopLeft, int width, int
height, int startAngle, int arcAngle);
}
}
static int CENTER_BASELINE The baseline used in ideographic scripts like Chinese, Japanese,
and Korean when laying out text.
static DIALOG A String constant for the canonical family name of the logical
String font "Dialog".
static DIALOG_INPUT A String constant for the canonical family name of the logical
String font "DialogInput".
static int HANGING_BASELINE The baseline used in Devanigiri and similar scripts when laying
out text.
static int LAYOUT_NO_LIMIT_CONTEXT A flag to layoutGlyphVector indicating that text in the char array
after the indicated limit should not be examined.
static int LAYOUT_NO_START_CONTEXT A flag to layoutGlyphVector indicating that text in the char array
before the indicated start should not be examined.
static MONOSPACED A String constant for the canonical family name of the logical
String font "Monospaced".
static name The logical name of this Font, as passed to the constructor.
String
static int ROMAN_BASELINE The baseline used in most Roman scripts when laying out text.
static SANS_SERIF A String constant for the canonical family name of the logical
String font "SansSerif".
static SERIF A String constant for the canonical family name of the logical
String font "Serif".
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="FontClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontClass extends java.applet.Applet
{
Font f;
String m;
public void init()
{
f=new Font("Arial",Font.ITALIC,20);
m="Welcome to Java";
setFont(f);
}
public void paint(Graphics g)
{
Color c=new Color(0,255,0);
g.setColor(c);
g.drawString(m,4,20);
}
}
Color class
The Color class is used to create colors in the default RGB color space or colors in any color spaces
defined by a ColorSpace. Every color has an implicit alpha value of 1.0 or an explicit one provided in
the constructor. The alpha value defines the transparency of a color and can be represented by a float
value in the range 0.0 – 1.0 or 0 – 255. An alpha value of 1.0 or 255 means that the color is completely
opaque and an alpha value of 0 or 0.0 means that the color is completely transparent. When
constructing a Color with an explicit alpha or getting the color/alpha components of a Color, the color
components are never pre multiplied by the alpha component.
Field
• static Color black -- The color black.
• static Color BLACK -- The color black.
• static Color blue -- The color blue.
• static Color BLUE -- The color blue.
• static Color cyan -- The color cyan.
• static Color CYAN -- The color cyan.
• static Color DARK_GRAY -- The color dark gray.
• static Color darkGray -- The color dark gray.
• static Color gray -- The color gray.
• static Color GRAY -- The color gray.
• static Color green -- The color green.
• static Color GREEN -- The color green.
• static Color LIGHT_GRAY -- The color light gray.
• static Color lightGray -- The color light gray.
• static Color magenta -- The color magenta.
• static Color MAGENTA -- The color magenta.
• static Color orange -- The color orange.
• static Color ORANGE -- The color orange.
• static Color pink -- The color pink.
• static Color PINK -- The color pink.
• static Color red -- The color red.
• static Color RED -- The color red.
• static Color white -- The color white.
• static Color WHITE -- The color white.
• static Color yellow -- The color yellow.
• static Color YELLOW -- The color yellow
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Font plainFont = new Font("Serif", Font.PLAIN, 24);
g2.setFont(plainFont);
g2.setColor(Color.red);
g2.drawString("Welcome to TutorialsPoint", 50, 70);
g2.setColor(Color.GRAY);
g2.drawString("Welcome to TutorialsPoint", 50, 120);
}
}