Chap 2 Applet
Chap 2 Applet
Applets are small programs that are used to prepare web applications and run over the internet. To start with
applet, first of all remember that Applet is a library class which comes under java.applet and we also need to import
java.awt packages. Remember that applets are not like console programs that executes with command based runtime
interpreter. Applets are programs specially designed for web applications and are executed using a web browser or
appletviewer.
An applet program do not have main( ) method to start execution but there are some applet methods which are
needed to be overridden in a user defined class that extends Applet class. Execution sequence of these applet methods
is fixed. We will study these all methods in applet’s life cycle. As applet do not concern with console programming,
hence the input and output statements we used till now are not applicable now onwards. Instead of that we will use
AWT components for that purpose. AWT stands for Abstract Window Toolkit.
Once an applet program is compiled, it is executed by using a web browser or appletviewer. To execute an
applet program we have to set up APPLET tag in the same program - as a comment or by providing a separate
HTML file. This APPLET tag is shown in following example.
<applet code = “applet_class_name.class” width = “width_in_pixels” height = “height_in_pixels”>
</applet>
As mentioned above, either place this tag in the same program as a multiline comment (/* …… */) or create a
separate HTML file containing this tag. Both the execution processes are discussed in this chapter.
To create an applet first of all we have to extend a user defined class with library class Applet by using keyword
extends. For example,
class apl1 extends Applet
{
------------ // define applet methods here
------------
}
Here, the class apl1 is inheriting the library class Applet and hence has to override Applet class’ methods. The
Applet class contains actually 24 methods. We can override them in our class as per requirement. Some of them are
shortly discussed here.
void init( )
Will be executed when an applet begins its execution. This is the first method of an applet to be executed.
void start( )
This method will be executed automatically after init( ) method.
void paint(Graphics obj)
This method redraws the applet output. Generally used to draw graphical objects in the applet.
void stop( )
This method will be called by the browser to suspend the execution of the applet. Once an applet is stopped, it will
begin from start( ) method.
void destroy( )
Called after stop( ) to perform any cleanup before destruction of the applet.
String getAppletInfo( )
Returns a string containing information of applet.
URL getCodeBase( )
Returns the URL concern with the invoking applet.
boolean isActive( )
Returns true if applet is started, otherwise false.
void play(URL url)
plays an audio clip, if present at specified url.
void resize(int w, int h)
resizes the applet with specified width w and height h.
Fig. 11.2.1
➢ Program 11.2.1 :
import java.awt.*;
import java.applet.*;
public class appl_demo extends Applet
{
public void init( )
{
// this method executes first and only once when applet is initially loaded.
}
public void start( )
{
// this method will be called second, after init( ) method and called each time.
}
public void paint(Graphics g)
{
// used to draw graphical objects using object g.
}
public void stop( )
{
// executes when applet is stopped or when controls leaves a page.
}
public void destroy( )
{
// executes after stop( ). This is the last method to be executed.
}
}
Although, above program is not able to display any output contents, but still you can see this appletviewer
screen as output.
Note : Do not forget to make the applet class as public. If you forget it, then in the same appletviewer screen, you will see
“Applet not initialized” at the bottom.
HEIGHT
A mandatory attribute that specifies the height of applet’s display area, in pixels.
WIDTH
A mandatory attribute that specifies the width of applet’s display area, in pixels.
CODEBASE
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.
ALT
An optional attribute that specifies a short alternate message that will be displayed if the web browser understands the
<applet> tag but cannot run Java applets, currently.
NAME
An optional attribute that is to specify an alternate name for the applet’s instance.
ALIGN
An optional attribute that specifies the alignment of applet.
VSPACE
An optional attribute that specifies vertical space i.e. to leave above and below the applet, in pixels.
HSPACE
An optional attribute that specifies vertical space i.e. to leave on both sides of the applet, in pixels.
This <PARAM> tag must be inside <APPLET> tag. This passed parameter is received in Java program by using
getParameter( ) method. This method is defined as:
➢ Program 11.5.1
import java.awt.*;
import java.applet.*;
public class param_demo extends Applet
{
String st;
public void init()
{
st=getParameter("argument");
st = "Hello " + st +"!";
}
public void paint(Graphics g)
{
g.drawString(st,100,100);
}
}
Now, lets create HTML file containing <PARAM> tag.
Call this file as two.html
<html>
<head>
<title>PARAM tag demo</title>
</head>
<body>
<applet code="param_demo.class" width="300" height="300">
<param name = "argument" value = "James">
</applet>
</body>
</html>
After executing above html file using appletviewer we can get following output.
11.6 Event handling in applet
Event handling is Applet also supports all the event classes and event listener interfaces that are shown in section
10.9. Before going through following programs that demonstrates event handling in Applets, first go through the
Table 10.9.1, Table 10.9.2 and Table 10.9.3.
We can easily implement all the example programs of section 10.9.5 (that are demonstrating event handling in
Frame) into Applet.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code= “mouse _demo” width= “400” height= “700” >
</applet>
*/
Here, MouseListener interface is implemented to handle mouse related events and all its methods are overridden in
implementing class mouse_demo. It is registered for events by using addMouseListener( ) method. Each time when
an event occurs, value of String changes and repaint( ) method is used to invoke paint( ) method manually,
whenever required. Whenever mouse event is performed, the MouseListener recognize the type of event and call to
related method. Here is the output of above program.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code= “key _demo” width= “400” height= “700” >
</applet>
*/
Here, KeyListener interface is implemented to handle Key related events. It is registered by using addKeyListener( )
method. The showStatus( ) method is used to display any user defined message on the status bar. The getKeyChar( )
method returns the character which is pressed for performing that event. Here is the output of above program.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class mouse_drag_move extends Applet implements MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseMotionListener(this);
}
The getX( ) and getY( ) methods retrieves the position of mouse pointer on X and Y axis, respectively. Refer following
output.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
/*
<applet code="checkbox_event" width="400" height="400">
</applet>
*/
Three Checkboxes are registered for ItemEvent and hence on each change of state of each checkboxes the method
itemStateChanged( ) gets invoked and we update the labels according to state of checkbox. Following is the output
of above program.
➢ Program 11.6.6 : an applet to display scrolling text from right to left in an applet window.
import java.awt.*;
import java.applet.*;
/*
<applet code="ScrollText" height="100" width="350">
</applet>
*/
Above Fig 11.7.1, shows that (0,0) coordinates are in top left corner of your screen. Here are some of the methods
required to study.
Remember that, all these methods are member functions of library class Graphics and draw them in paint( ) methods
of applet class.
➢ Program 11.7.1 :
import java.awt.*;
import java.applet.*;
/ * <applet code = “string_demo.class” height = “300” width = “300”> </applet> */
public class string_demo extends Applet
{
public void paint(Graphics g)
{
g.drawString("String demo",60,100);
}
}
Output of above applet will be :
import java.awt.*;
import java.applet.*;
/ * <applet code = “line_demo.class” height = “300” width = “300”> </applet> */
public class line_demo extends Applet
{
public void paint(Graphics g)
{
g.drawLine(40,75,110,190);
g.setColor(Color.red);
g.drawLine(140,100,200,290);
g.setColor(Color.blue);
g.drawLine(25,65,150,210);
g.setColor(Color.green);
g.drawLine(70,90,130,135);
g.setColor(Color.yellow);
g.drawLine(95,125,175,230);
}
}
Above program will show following output in appletviewer.
import java.awt.*;
import java.applet.*;
/ * <applet code = “rect_demo.class” height = “300” width = “300”> </applet> */
public class rect_demo extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10, 10, 60, 50);
g.fillRect(110, 90, 40, 30);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(60, 170, 140, 100, 30, 40);
}
}
Above program will show following output.
Tip : To draw a perfect rectangle, keep the width and height equal.
To draw ellipses and circles we have drawOval( ) and fillOval( ) mehods. The general form of these methods are:
void drawoval(int startX, int startY, int width, int height)
void filloval(int startX, int startY, int width, int height)
The general syntax of drawing oval is same as of drawing rectangle.
These methods, first generate a bounding rectangle and join midpoint points of each side and draw an oval.
➢ Program 11.7.4 :Program to demonstrates drawing & filling ellipses and circles with different colors
import java.awt.*;
import java.applet.*;
/ * <applet code = “oval_demo.class” height = “300” width = “300”> </applet> */
public class oval_demo extends Applet
{
public void paint(Graphics g)
{
g.drawoval(10, 10, 60, 60);
g.filloval(110, 90, 40, 40);
g.drawoval(190, 10, 60, 60);
g.filloval(60, 170, 140, 60);
}
}
After successful compilation and execution using appletviewer, output of above program will be :
Tip : To draw a perfect circle, keep the width and height equal.
Arcs can also be drawn and filled by using graphical methods. General syntax to draw and fill arc is :
void drawArc(int startX, int startY, int width, int height, int startAngle, int sweepAngle)
void fillArc(int startX, int startY, int width, int height, int startAngle, int sweepAngle)
These methods also generates a bounding rectangle and the arc is drawn from startAngle through the angular distance
specified by sweepAngle. We specify the angles in terms of degree. The negative angle draws arc clockwise
and positive angle draws arc counterclockwise.
import java.awt.*;
import java.applet.*;
/ * <applet code = “arc_demo.class” height = “300” width = “300”> </applet> */
public class arc_demo extends Applet
{
public void paint(Graphics g)
{
g.drawArc(10, 40, 70, 70, 0, 75);
g.setColor(Color.cyan);
g.fillArc(100, 40, 70, 70, 0, 75);
g.setColor(Color.pink);
g.drawArc(10, 100, 70, 80, 0, 175);
g.setColor(Color.black);
g.fillArc(100, 100, 70, 90, 0, 270);
g.setColor(Color.magenta);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}
Above applet program will show following applet output.
import java.awt.*;
import java.applet.*;
/ * <applet code = “poly_demo.class” height = “300” width = “300”> </applet> */
public class poly_demo extends Applet
{
public void paint(Graphics g)
{
int x1[]={30,200,30};
int y1[]={30,30,200};
int x2[]={200,200,30};
int y2[]={30,200,200};
g.drawPolygon(x1,y1,3);
g.fillPolygon(x2,y2,3);
}
}
Above program will produce following output.
Applet Application
Needs no explicit installation on local machine. Can be Stand Alone, doesn’t need web-browser.
transferred through Internet on to the local machine and
may run as part of web-browser.
Execution starts with init() method. Does work without Execution starts with main( ) method.
main( ) method. Doesn’t work if main( ) method is not there.
Must run within a GUI (Using AWT or Swing May or may not be a GUI.
components).
Requires high security, as they are untrusted. Does not require any security, as they are
installed on the same machine.
From above differentiation, we cannot say that applets more valuable then applications. Both of these have their own
advantages and disadvantages over each other. But truly speaking, if I suggest you to choose one, between them, then
we will definitely prefer applets. It is because they are centrally managed and their upgradations are easy. Even they
have a centralized database; hence easy to access from anywhere in the world. Let’s List out the important advantages
and limitations of applets over application.
Advantages of applet
• Execution of applet does not require any installation or deployment procedure.
• Centrally managed, hence easy to upgrade and access.
• Platform independent.
• Writing and displaying animations and graphics are very much easy.
• Databases are centrally stored, hence can be accessed from anywhere.
Limitations of applet
• Each time during the real time environment, the Bytecodes of applet are to be downloaded from server. Hence
requires internet data.
• Applets are treated as untrusted therefore requires high security.