Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

ES05-Object Oriented Programming FE SEM II Mandar Sohani

Module 6
Applets
The goal for HTML was to create a platform-independent language for constructing
hypertext documents to communicate multimedia information easily over the Internet.
Using an Internet protocol called Hyper-Text Transport Protocol (HTTP), HTML
documents could be transmitted to any user on the Internet and displayed by software
called a browser.

The Structure and Function of HTML


The following code shows a minimal HTML document that can be displayed in Internet
Explorer or Netscape Navigator:

<HTML>
<HEAD>
<TITLE>The Title</TITLE>
</HEAD>
</HTML>

As the name suggests, HTTP is a protocol used for transferring hypertext documents
across the Web. A protocol is a specification for communicating information URLs
URL stands for Uniform Resource Locator. The word Uniform in this case means that the
syntax follows a standard convention, even when extended into new addresses. Resource
means anything that has an identity, such as a file, a program, an image, and so forth. A
URL includes the following components:

• http://—The http refers to the overall protocol being used, and following that must be
the colon and two forward slashes.
• The name of the host computer on which the resource resides. Typically this is the
domain name (for example, www.mu.ac.in).
• The port on which the Web server is listening—this is typically 80, and must be
preceded by a colon (:). This is usually omitted and assumed to be :80. Ports are logical
addresses to which messages may be sent in an operating system.
• The absolute path, preceded by a forward slash (/), to the folder where the file is
located, including the filename.
For example, a typical URL might be www.e4free.com/asubfolder/afile.htm.
• If there is a query attached to the URL, it begins with a question mark, and the
name/value pairs in the query are separated by ampersands.

Applet Fundamentals
Applets are small applications that are accessed on an Internet server, transported over
the Internet, automatically installed, and run as part of a Web document.
Applets interact with the user through the AWT, not through the console-based I/O
classes. The AWT contains support for a window-based, graphical interface.
Every applet that is being created must be a subclass of Applet.

1
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

Running SimpleApplet involves a different process.


Two ways to run an applet:
■ Executing the applet within a Java-compatible Web browser.
■ Using an applet viewer, such as the standard SDK tool, appletviewer.

An applet viewer executes the applet in a new separate window. This is generally the
fastest and easiest way to test the applet.

1. Executing applet in web browser:


To execute an applet in a Web browser, write a short HTML text file that contains the
appropriate APPLET tag. Here is the HTML file that executes SimpleApplet:

<HTML>
<HEAD>
<TITLE>The Title</TITLE>
<applet code="SimpleApplet" width=200 height=60>
</applet>
</HEAD>
</HTML>

The width and height statements specify the dimensions of the display area used by the
applet.

2. Executing applet by using appletviewer:


To execute SimpleApplet with an applet viewer, execute the HTML file shown earlier.
For example, if the preceding HTML file is called RunApp.html, then the following
command line will run SimpleApplet:

C:\>appletviewer RunApp.html

OR
Include the APPLET tag as a comment at the beginning of Java source code file
1. Edit a Java source file.
2. Compile the program.
3. Execute the applet viewer, specifying the name of the applet’s source file.
The applet viewer will encounter the APPLET tag within the comment and execute
the applet.

import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet
2
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

{
public void paint(Graphics g)
{
g.drawString("A Java Applet Programming", 20, 20);
}
}

All applets are subclasses of Applet. Thus, all applets must import java.applet.
Applets must also import java.awt.
Execution of an applet does not begin at main( ). Actually, few applets even have
main( ) methods.

The HTML APPLET Tag:


The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.
The syntax for the standard APPLET tag is shown here. Bracketed items are optional.
< APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT =
alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] >
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
</APPLET>

CODEBASE:
CODEBASE is an optional attribute that specifies the base URL of the applet code,
which is the directory that will be searched for the applet’s executable class file (specified
by the CODE tag). The HTML document’s URL directory is used as the CODEBASE if
this attribute is not specified. The CODEBASE does not have to be on the host from
which the HTML document was read.

CODE:
CODE is a required attribute that gives the name of the file containing the applet’s
compiled .class file. This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by CODEBASE if set.

ALT:
The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser understands the APPLET tag but can’t currently run Java
applets.

NAME:
NAME is an optional attribute used to specify a name for the applet instance. Applets
must be named in order for other applets on the same page to find them by name and
communicate with them.

WIDTH AND HEIGHT:


3
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet
display area.

ALIGN:
ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is
treated the same as the HTML IMG tag with these possible values:
LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE,
and ABSBOTTOM.

VSPACE AND HSPACE:


These attributes are optional. VSPACE specifies the space, in pixels, above and below
the applet. HSPACE specifies the space, in pixels, on each side of the applet. They’re
treated the same as the IMG tag’s VSPACE and HSPACE attributes.

PARAM NAME AND VALUE:


The PARAM tag allows to specify applet specific arguments in an HTML page. Applets
access their attributes with the getParameter( ) method.

Passing Parameters to Applets:


The APPLET tag in HTML allows to pass parameters to the applet. To retrieve a
parameter, use the getParameter( ) method. It returns the value of the specified parameter
in the form of a String object.

import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
</applet>
*/
public class ParamDemo extends Applet
{
String fontName;
int fontSize;
public void start()
{
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try
{
if(param != null)
fontSize = Integer.parseInt(param);
4
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

else
fontSize = 0;
}
catch(NumberFormatException e)
{
fontSize = -1;
}
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
}
}

The Applet Class:


Applet provides all necessary support for applet execution, such as starting and stopping.
It also provides methods that load and display images, and methods that load and play
audio clips.
Applet extends the AWT class Panel. In turn, Panel extends Container, which extends
Component. These classes provide support for Java’s window-based, graphical interface.
Thus, Applet provides all of the necessary support for window-based activities.

Methods of Applet class:


1. void destroy( )
Called by the browser just before an applet is terminated. User applet will override
this method if it needs to perform any cleanup prior to its destruction.
2. String getAppletInfo( )
Returns a string that describes the applet.
3. AudioClip getAudioClip(URL url)
Returns an AudioClip object that encapsulates the audio clip found at the location
specified by url.
4. AudioClip getAudioClip(URL url, String clipName)
Returns an AudioClip object that encapsulates the audio clip found at the location
specified by url and having the name specified by clipName.
5. Image getImage(URL url)
Returns an Image object that encapsulates the image found at the location specified
by url.
6. Image getImage(URL url, String imageName)
Returns an Image object that encapsulates the image found at the location specified
by url and having the name specified by imageName.
7. String getParameter(String paramName)
Returns the parameter associated with paramName. null is returned if the specified
parameter is not found.
8. void init( )
Called when an applet begins execution. It is the first method called for any applet.
9. boolean isActive( )
5
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

Returns true if the applet has been started. It returns false if the applet has been
stopped.
10. void play(URL url)
If an audio clip is found at the location specified by url, the clip is played.
11. void play(URL url, String clipName)
If an audio clip is found at the location specified by url with the name specified
by clipName, the clip is played.
11. void start( )
Called by the browser when an applet should start (or resume) execution. It is
automatically called after init( ) when an applet first begins.
12. void stop( )
Called by the browser to suspend execution of the applet. Once stopped, an applet is
restarted when the browser calls start( ).

The applet life cycle:


When an applet begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

6
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

init( )
The init( ) method is the first method to be called. This method is can be used to
initialize variables. This method is called only once during the run time of the applet.

start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is
called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a
web page and comes back, the applet resumes execution at start( ).

paint( )
The paint( ) method is called each time the applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is
running may be overwritten by another window and then uncovered. Or the applet
window may be minimized and then restored. paint( ) is also called when the applet
begins execution. Whatever the cause, whenever the applet must redraw its output,
paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is
running. This context is used whenever output to the applet is required.

stop( )
The stop( ) method is called when a web browser leaves the HTML document containing
the applet—when it goes to another page, for example. When stop( ) is called, the applet
is probably running.

destroy( )
The destroy( ) method is called when the environment determines that the applet needs to
be removed completely from memory. It should be used to free up any resources the
applet may be using. The stop( ) method is always called before destroy( ).

Working with Graphics:


The AWT supports many graphics methods. All graphics are drawn relative to a
window.
The origin of each window is at the top-left corner and is 0,0. Coordinates are specified in
pixels. All output to a window takes place through a graphics context.
A graphics context is encapsulated by the Graphics class and is obtained in two ways:
■ It is passed to an applet when one of its various methods, such as paint( ) or update( ),
is called.
■ It is returned by the getGraphics( ) method of Component.

The Graphics class defines a number of drawing functions. Each shape can be drawn
edge-only or filled. Objects are drawn and filled in the currently selected graphics color,
which is black by default. When a graphics object is drawn that exceeds the dimensions
of the window, output is automatically clipped.

7
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

Drawing Lines:
Lines are drawn by means of the drawLine( ) method, shown here:

void drawLine(int X1, int Y1, int X2, int Y2)


drawLine( ) displays a line in the current drawing color that begins at X1,Y1 and
ends at X2,Y2.
The following applet draws several lines:
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 height=200>
</applet>
*/
public class Lines extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
}
}

Drawing Rectangles:
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle,
respectively. They are shown here:

void drawRect(int X, int Y, int width, int height)


void fillRect(int X, int Y, int width, int height)
The X,Y specifies the coordinates of top left corner. The dimensions of the rectangle are
specified by width and height.

To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both


shown here:
void drawRoundRect(int X, int Y, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int X, int Y, int width, int height, int xDiam, int yDiam)
A rounded rectangle has rounded corners. The dimensions of the rectangle are specified
by width and height. The diameter of the rounding arc along the X axis is specified by
xDiam. The diameter of the rounding arc along the Y axis is specified by yDiam.

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet
8
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

{
public void paint(Graphics g)
{
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}

Drawing Ellipses and Circles:


To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods
are shown here:

void drawOval(int X, int Y, int width, int height)


void fillOval(int X, int Y, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified
by X,Y and whose width and height are specified by width and height.
To draw a circle, specify a square as the bounding rectangle.
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
public class Ellipses extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}

Drawing Arcs:
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:

void drawArc(int X, int Y, int width, int height, int startAngle, int sweepAngle)
void fillArc(int X, int Y, int width, int height, int startAngle, int sweepAngle)

The arc is bounded by the rectangle whose upper-left corner is specified by X,Y and
whose width and height are specified by width and height. The arc is drawn from
startAngle through the angular distance specified by sweepAngle. Angles are specified in
9
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

degrees. Zero degrees is on the horizontal, at the three o’clock position. The arc is drawn
counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is negative.
Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle would be 90
and the sweep angle 180.

import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 height=200>
</applet>
*/
public class Arcs extends Applet
{
public void paint(Graphics g)
{
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75);
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}

Drawing Polygons:
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),
shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and
y arrays. The number of points defined by x and y is specified by numPoints.
import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
{
public void paint(Graphics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num); LIBRARY
}
}
10
Notes by – Mandar Sohani
CO6: Develop web based applications.
ES05-Object Oriented Programming FE SEM II Mandar Sohani

Working with Color:


Color is encapsulated by the Color class. Color defines several constants (for example,
Color.black) to specify a number of common colors.It support to create required colors,
using one of the color constructors. The most commonly used forms are shown here:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red, green,
and blue. These values must be between 0 and 255, as in this example:
new Color(255, 100, 100); // light red.

import java.awt.*;
import java.applet.*;
/*
<applet code="ColorDemo" width=300 height=200>
</applet>
*/
public class ColorDemo extends Applet
{
public void paint(Graphics g)
{
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
g.setColor(c1);
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.setColor(c2);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.setColor(c3);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
g.setColor(Color.red);
g.drawOval(10, 10, 50, 50);
g.fillOval(70, 90, 140, 100);
g.setColor(Color.blue);
g.drawOval(190, 10, 90, 30);
g.drawRect(10, 10, 60, 50);
g.setColor(Color.cyan);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
}
}

11
Notes by – Mandar Sohani
CO6: Develop web based applications.

You might also like