Applet Programming in Java
 By
VIKRANTH B.M.
 FACULTY
 CSE DEPARTMENT
APPLET PROGRAMMING
Applets are small applications that are accessed on
an internet Server, transported over the internet,
automatically installed and run as a Part of web
document.
After the applet arrives on the client, it has Limited
access to resources.
Eg Program
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet{
public void paint(Graphics g) {
g.drawString(“Hello World”,20,30);
}
}
Applet Interaction
 Applets Interact with the user through the
AWT,not through the console based I/O
classes.
 The AWT supports for window based
graphical interface.
 The second import stmt imports the applet
package,which contains the class Applet.
 Every class You create must be a Subclass
of applet. Paint() is called each time that the
applet must redisplay its output.
 Whenever the applet must redraw its
output,paint() is called.
 The Paint() method has one parameter of
type Graphics.This parameter contains the
graphics context,which describes the
graphics environment in which the applet is
running.
 Inside paint() is a call to drawstring() which
is a member of graphics class.This method
outputs a string beginning at the specified X,Y
location.
 The general form
 Void drawString(String message,int x, int y);
 Two ways of executing applet
 .)Java Compatible Web Browser
 .)AppletViewer
Executing a APPLET
 To execute an applet in a web
browser,you need to write a short HTML
text file that contains the appropriate
APPLET Tag.
 <applet code=“SimpleApplet” width=200
height=60>
 </applet>
 To execute SimpleApplet with an Applet
viewer,you may also execute the HTML
file shown earlier.For Eg
 C:>appletviewer SimpleApplet.html
 However a more convenient method
exists that you can use to speed up
testing.
 Simply include a comment at the head
of your java source code file that
contains the applet tag.
 By doing so your code is documented
with a prototype of the necessary HTML
statements and you can test your
compiled applet merely by starting the
apple viewer
with your java source code file.
Eg
import java.awt.*;
import java.applet.*;
/*
<applet code=“SimpleApplet” width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet{
public void paint(Graphics g) {
g.drawString(“Hello World”,20,30);
} }
Applet development involves three steps
.)Edit a Java Source file
.)Compile your program
.)Execute the applet viewer,specifying the name of your
applet’s source.
 Applets do not need a main() method.
 Applets must be run under an applet viewer
or a java compatible web browser.
 User I/O is not accomplished with java’s
stream I/O classes.Instead applets use the
Interface provide by the awt.
 .)Applets are event driven.An Applet
Resembles a set of Interrupt service
routines.
 An Applet waits until an event occurs.The
AWT notifies the applet about an event by
calling the event handler that has been
provided by the applet.
 Once this happens the applet must take
appropriate action and then quickly return
control to the AWT run time system.
Applet Skeleton
//an Applet Skeleton
import java.awt.*;
import java.applet.*;
/*
<applet code=“Appletskel” width=300
height=100>
</applet>
*/
public class Appletskel extends Applet{
//called first
 public void init()
 { // initialization }
 /* called second after init().Also called
whenever the applet is restarted */
 Public void start() { // start or resume
execution }
 Public void stop() { }
 // called when a web browser leaves the
Html doc containing an applet.
 Public void paint(Graphics g){
 //redisplay the contents of the window
 }
public void destroy(){
// perform shutdown activities }
}
Applet Initialization and Termination
When an applet begins, the AWT calls the following
methods in this sequence.
.)init() .)start() .)paint()
When an applet is terminated the following sequence of
methods calls take place.
1. stop();
2. Destroy();
Applets Methods
 Init()
The init() method is the first method to be
called.This is where you should initialize
variables.This method is called only once
During the run time of your applet.
Start()
The start() method is called after init().It is also
called to restart an applet after it has been
stopped.
The start() is called each time an applet’s HTML
doc is displayed onscreen.
 Paint()
Paint() method is called each time your
applet’s output must be redrawn.Paint() is
also called when the applet begins
execution.
Whenever the applet must redraw its
output
Paint() is called.
Stop()
The stop() method is called when a web
browser leaves the HTML doc containing
the
 destroy()
 The destroy() method is called when the
environment determines that your
applet needs to be removed completely
from memory.
OverRiding Update
 Your applet may need to override
another method defined by awt called
update().This method is called when
your applet has requested that a portion
of its window be redrawn.
 The default version of update() first fills
an applet with the default background
color and then calls paint(),the user will
experience a flash of the default
background each time update() is
called,I,e
 Whenever the window is repainted
 One way to avoid this problem is to
override the update() method so that it
performs all necessary display activities.
 Then have paint() simple calls update()
 public void update(Graphics g) {
 // redisplay your window here
 }
 Public void paint(Graphics g)
 { Update(g); }
A very Simple Applet Program
import java.awt.*;
import java.applet.*;
/*<appletcode=“Sample” width=300 height=50> </applet>
*/
Public class sample extends Applet {
String msg;
//set the foreground and background colors
public void init(){
setBackground(color.cyan);
setForeground(color.red);
msg=“Inside init()…”;
}
Public void start(){
msg+=“Inside start()----”; }
 //Displaying msg in applet window
public void paint(Graphics g) {
msg+=“Inside paint()”;
g.drawString(msg,10,30);
}
}
Requesting Repainting
 An applet writes to its window only when its update()
or paint() method is called by awt.
 How can the applet itself cause its window to be
updated when its information changes.
 For Eg if an applet is displaying a moving banner
what mechanism does the applet use to update the
window each time this banner scrolls.
 It cannot create a loop inside paint() that repeatedly
scrolls the banner.
 Whenever your applet needs to update the
information displayed in its window,it simply calls
repaint().
The repaint() method is defined by awt.
It causes the awt run time system to
execute call to your applet’s update()
method, which in its default
implementation calls paint().
If part of ur applet needs to output a
string,it can store this string in a string
variable and then call repaint()
 Remember, one of the fundamental
architectural constraints imposed on an
 applet is that it must quickly return
control to the awt run-time system. It
cannot create a loop inside paint( )that
repeatedly scrolls the banner, for
example. This would prevent control
from passing back to the AWT.
 Whenever your applet needs to update
the information displayed in its window,
it simply calls repaint( ).
Simple Banner Applet
/* A simple banner applet.
This applet creates a thread that scrolls
the message contained in msg right to left
across the applet's window.
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/
public class SimpleBanner extends Applet implements
Runnable {
String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopflag;
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
// Entry point for the thread that runs the banner.
public void run() {
char ch;
// Display banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
}
}
 // Pause the banner.
 public void stop() {
 stopFlag = true;
 t = null;
 }
 // Display the banner.
 public void paint(Graphics g) {
 g.drawString(msg, 50, 30);
 }
 }
Using the Status Window
 an applet can also output a message to the status
window of the browser or applet viewer on which it is
running. To do so, call showStatus( )with the string
that you want displayed.
 The status window also makes an excellent
debugging aid, because it gives you an easy way to
output information about your applet.
 The status window is a good place to give the user
feedback about what is occurring in the applet,
suggest options, or possibly report some types of
errors.
 // Using the Status Window.
 import java.awt.*;
 import java.applet.*;
 /*
 <applet code="StatusWindow" width=300 height=50>
 </applet>
 */
 public class StatusWindow extends Applet{
 public void init() {
 setBackground(Color.cyan);
 }
 // Display msg in applet window.
 public void paint(Graphics g) {
 g.drawString("This is in the applet window.", 10, 20);
 showStatus("This is shown in the status window.");
 }
 }
Output
The HTML APPLET Tag
 An appletviewer will execute each APPLET tag that it finds in a
separate window, while web browsers will allow many applets on
a single page. So far, we have been using only a simplified form
of the APPLET tag. Now it is time to take a closer look at it.
 < APPLET
 [CODEBASE = codebaseURL ]
 CODE = appletFile
 [ALT = alternateText]
 [NAME = appletInstanceName]
 WIDTH =pixels HEIGHT = pixels
 [ALIGN = alignment]
 [VSPACE = pixels] [HSPACE = pixels]
 >
 [< PARAM NAME = AttributeNameVALUE =AttributeValue>]
 [< PARAM NAME = AttributeName2 VALUE =AttributeValue>]
 . . .
 [HTML Displayed in the absence of Java ]
 </APPLET>
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’sURL directory is used as the
CODEBASE.
CODE is a required attribute that gives the
name of the file containing your 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
ALT The tag is an optional attribute used
to specify a short text message that
should be displayed if the browser
recognizes the APPLET tag but can’t
currently run Java applets.
Passing Parameters to Applets
APPLET tag in HTML allows you to pass
parameters to your applet.
To retrieve a parameter, use the
getParamet
er( ) method. It returns the value of the
specified parameter in the form of a String
object.
Thus, for numeric and boolean values, you
will
need to convert their string
Passing Parameters to Applet
As just discussed, the APPLET tag in HTML allows
you to pass parameters to your applet.
To retrieve a parameter, use the getParameter( )
method. It returns the value of the specified,
parameter in the form of a String object.
Thus, for numeric and boolean values, you will need
to convert their string representations into their
internal formats.
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if found
fontSize = Integer.parseInt(param);
else
 fontSize = 0;
 } catch(NumberFormatException e) {
 fontSize = -1;
 }
 param = getParameter("leading");
 try {
 if(param != null) // if found
 leading = Float.valueOf(param).floatValue();
 else
 leading = 0;
 } catch(NumberFormatException e) {
 leading = -1;
 }
 param = getParameter("accountEnabled");
 if(param != null)
 active = Boolean.valueOf(param).booleanValue();
 }
 // Display parameters.
 public void paint(Graphics g) {
 g.drawString("Font name: " + fontName, 0,
10);
 g.drawString("Font size: " + fontSize, 0, 26);
 g.drawString("Leading: " + leading, 0, 42);
 g.drawString("Account Active: " + active, 0,
58);
 }
 }
getDocumentBase( ) and
getCodeBase( )
 Java will allow the applet to load data from
the directory holding the HTML file that started
the applet (the document base ) and the
directory from which the applet’s class file was
loaded (the code base ).
 These directories are returned as URLobjects
by getDocumentBase( )and getCodeBase( ) .
They can be concatenated with a string that
names
 the file you want to load
AppletContext and showDocument( )
To allow your applet to transfer control to
another URL, you must use the
showDocument( ) method defined by the
AppletContext interface.
AppletContext is an interface that lets you get
information from the applet’s execution
environment.
The context of the currently executing applet is
obtained by a call to the
getAppletContext()method defined byApplet.
AppletContext and showDocument( )
Within an applet, once you have obtained
the applet’s context, you can bring
another document into view by calling
showDocument( ).
. This method has no return value and
throws no exception if it fails, so use it
carefully.
There are two showDocument(
)methods.
showDocument(URL) displays the
document at the specified URL.
The method showDocument(URL, String)
displays the specified document at the
specified location within the browser
window.
Valid arguments for where are “_self”
(show in current frame)._parent” (show in
parent frame), “ “_top” (show in topmost
frame) and “_blank” (show in new
browser window).
The following applet demonstrates
AppletContext and showDocument( ) .
Upon execution,it obtains the current
applet context and uses that context to
transfer control to a file called Test.html.
This file must be in the same directory as
the applet. Test.html can contain any
valid hypertext that you like.
Applet progming

Applet progming

  • 1.
    Applet Programming inJava  By VIKRANTH B.M.  FACULTY  CSE DEPARTMENT
  • 2.
    APPLET PROGRAMMING Applets aresmall applications that are accessed on an internet Server, transported over the internet, automatically installed and run as a Part of web document. After the applet arrives on the client, it has Limited access to resources. Eg Program import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet{ public void paint(Graphics g) { g.drawString(“Hello World”,20,30); } }
  • 3.
    Applet Interaction  AppletsInteract with the user through the AWT,not through the console based I/O classes.  The AWT supports for window based graphical interface.  The second import stmt imports the applet package,which contains the class Applet.  Every class You create must be a Subclass of applet. Paint() is called each time that the applet must redisplay its output.  Whenever the applet must redraw its output,paint() is called.
  • 4.
     The Paint()method has one parameter of type Graphics.This parameter contains the graphics context,which describes the graphics environment in which the applet is running.  Inside paint() is a call to drawstring() which is a member of graphics class.This method outputs a string beginning at the specified X,Y location.  The general form  Void drawString(String message,int x, int y);  Two ways of executing applet  .)Java Compatible Web Browser  .)AppletViewer
  • 5.
    Executing a APPLET To execute an applet in a web browser,you need to write a short HTML text file that contains the appropriate APPLET Tag.  <applet code=“SimpleApplet” width=200 height=60>  </applet>  To execute SimpleApplet with an Applet viewer,you may also execute the HTML file shown earlier.For Eg  C:>appletviewer SimpleApplet.html
  • 6.
     However amore convenient method exists that you can use to speed up testing.  Simply include a comment at the head of your java source code file that contains the applet tag.  By doing so your code is documented with a prototype of the necessary HTML statements and you can test your compiled applet merely by starting the apple viewer with your java source code file. Eg
  • 7.
    import java.awt.*; import java.applet.*; /* <appletcode=“SimpleApplet” width=200 height=60> </applet> */ public class SimpleApplet extends Applet{ public void paint(Graphics g) { g.drawString(“Hello World”,20,30); } } Applet development involves three steps .)Edit a Java Source file .)Compile your program .)Execute the applet viewer,specifying the name of your applet’s source.
  • 8.
     Applets donot need a main() method.  Applets must be run under an applet viewer or a java compatible web browser.  User I/O is not accomplished with java’s stream I/O classes.Instead applets use the Interface provide by the awt.  .)Applets are event driven.An Applet Resembles a set of Interrupt service routines.  An Applet waits until an event occurs.The AWT notifies the applet about an event by calling the event handler that has been provided by the applet.  Once this happens the applet must take appropriate action and then quickly return control to the AWT run time system.
  • 9.
    Applet Skeleton //an AppletSkeleton import java.awt.*; import java.applet.*; /* <applet code=“Appletskel” width=300 height=100> </applet> */ public class Appletskel extends Applet{ //called first
  • 10.
     public voidinit()  { // initialization }  /* called second after init().Also called whenever the applet is restarted */  Public void start() { // start or resume execution }  Public void stop() { }  // called when a web browser leaves the Html doc containing an applet.  Public void paint(Graphics g){  //redisplay the contents of the window  }
  • 11.
    public void destroy(){ //perform shutdown activities } } Applet Initialization and Termination When an applet begins, the AWT calls the following methods in this sequence. .)init() .)start() .)paint() When an applet is terminated the following sequence of methods calls take place. 1. stop(); 2. Destroy();
  • 12.
    Applets Methods  Init() Theinit() method is the first method to be called.This is where you should initialize variables.This method is called only once During the run time of your applet. Start() The start() method is called after init().It is also called to restart an applet after it has been stopped. The start() is called each time an applet’s HTML doc is displayed onscreen.
  • 13.
     Paint() Paint() methodis called each time your applet’s output must be redrawn.Paint() is also called when the applet begins execution. Whenever the applet must redraw its output Paint() is called. Stop() The stop() method is called when a web browser leaves the HTML doc containing the
  • 14.
     destroy()  Thedestroy() method is called when the environment determines that your applet needs to be removed completely from memory.
  • 15.
    OverRiding Update  Yourapplet may need to override another method defined by awt called update().This method is called when your applet has requested that a portion of its window be redrawn.  The default version of update() first fills an applet with the default background color and then calls paint(),the user will experience a flash of the default background each time update() is called,I,e  Whenever the window is repainted
  • 16.
     One wayto avoid this problem is to override the update() method so that it performs all necessary display activities.  Then have paint() simple calls update()  public void update(Graphics g) {  // redisplay your window here  }  Public void paint(Graphics g)  { Update(g); }
  • 17.
    A very SimpleApplet Program import java.awt.*; import java.applet.*; /*<appletcode=“Sample” width=300 height=50> </applet> */ Public class sample extends Applet { String msg; //set the foreground and background colors public void init(){ setBackground(color.cyan); setForeground(color.red); msg=“Inside init()…”; } Public void start(){ msg+=“Inside start()----”; }
  • 18.
     //Displaying msgin applet window public void paint(Graphics g) { msg+=“Inside paint()”; g.drawString(msg,10,30); } }
  • 19.
    Requesting Repainting  Anapplet writes to its window only when its update() or paint() method is called by awt.  How can the applet itself cause its window to be updated when its information changes.  For Eg if an applet is displaying a moving banner what mechanism does the applet use to update the window each time this banner scrolls.  It cannot create a loop inside paint() that repeatedly scrolls the banner.  Whenever your applet needs to update the information displayed in its window,it simply calls repaint().
  • 20.
    The repaint() methodis defined by awt. It causes the awt run time system to execute call to your applet’s update() method, which in its default implementation calls paint(). If part of ur applet needs to output a string,it can store this string in a string variable and then call repaint()
  • 21.
     Remember, oneof the fundamental architectural constraints imposed on an  applet is that it must quickly return control to the awt run-time system. It cannot create a loop inside paint( )that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT.  Whenever your applet needs to update the information displayed in its window, it simply calls repaint( ).
  • 22.
    Simple Banner Applet /*A simple banner applet. This applet creates a thread that scrolls the message contained in msg right to left across the applet's window. */ import java.awt.*; import java.applet.*; /* <applet code="SimpleBanner" width=300 height=50> </applet> */ public class SimpleBanner extends Applet implements Runnable { String msg = " A Simple Moving Banner."; Thread t = null; int state;
  • 23.
    boolean stopflag; // Startthread public void start() { t = new Thread(this); stopFlag = false; t.start(); } // Entry point for the thread that runs the banner.
  • 24.
    public void run(){ char ch; // Display banner for( ; ; ) { try { repaint(); Thread.sleep(250); ch = msg.charAt(0); msg = msg.substring(1, msg.length()); msg += ch; if(stopFlag) break; } catch(InterruptedException e) {} } }
  • 25.
     // Pausethe banner.  public void stop() {  stopFlag = true;  t = null;  }  // Display the banner.  public void paint(Graphics g) {  g.drawString(msg, 50, 30);  }  }
  • 26.
    Using the StatusWindow  an applet can also output a message to the status window of the browser or applet viewer on which it is running. To do so, call showStatus( )with the string that you want displayed.  The status window also makes an excellent debugging aid, because it gives you an easy way to output information about your applet.  The status window is a good place to give the user feedback about what is occurring in the applet, suggest options, or possibly report some types of errors.
  • 27.
     // Usingthe Status Window.  import java.awt.*;  import java.applet.*;  /*  <applet code="StatusWindow" width=300 height=50>  </applet>  */  public class StatusWindow extends Applet{  public void init() {  setBackground(Color.cyan);  }  // Display msg in applet window.  public void paint(Graphics g) {  g.drawString("This is in the applet window.", 10, 20);  showStatus("This is shown in the status window.");  }  }
  • 28.
  • 29.
    The HTML APPLETTag  An appletviewer will execute each APPLET tag that it finds in a separate window, while web browsers will allow many applets on a single page. So far, we have been using only a simplified form of the APPLET tag. Now it is time to take a closer look at it.  < APPLET  [CODEBASE = codebaseURL ]  CODE = appletFile  [ALT = alternateText]  [NAME = appletInstanceName]  WIDTH =pixels HEIGHT = pixels  [ALIGN = alignment]  [VSPACE = pixels] [HSPACE = pixels]  >  [< PARAM NAME = AttributeNameVALUE =AttributeValue>]  [< PARAM NAME = AttributeName2 VALUE =AttributeValue>]  . . .  [HTML Displayed in the absence of Java ]  </APPLET>
  • 30.
    CODEBASE is an optionalattribute 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’sURL directory is used as the CODEBASE. CODE is a required attribute that gives the name of the file containing your 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
  • 31.
    ALT The tagis an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets.
  • 32.
    Passing Parameters toApplets APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParamet er( ) method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and boolean values, you will need to convert their string
  • 33.
    Passing Parameters toApplet As just discussed, the APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified, parameter in the form of a String object. Thus, for numeric and boolean values, you will need to convert their string representations into their internal formats. // Use Parameters import java.awt.*; import java.applet.*; /*
  • 34.
    /* <applet code="ParamDemo" width=300height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> */ public class ParamDemo extends Applet{ String fontName; int fontSize; float leading; boolean active;
  • 35.
    // Initialize thestring to be displayed. public void start() { String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found"; param = getParameter("fontSize"); try { if(param != null) // if found fontSize = Integer.parseInt(param); else
  • 36.
     fontSize =0;  } catch(NumberFormatException e) {  fontSize = -1;  }  param = getParameter("leading");  try {  if(param != null) // if found  leading = Float.valueOf(param).floatValue();  else  leading = 0;  } catch(NumberFormatException e) {  leading = -1;  }  param = getParameter("accountEnabled");  if(param != null)  active = Boolean.valueOf(param).booleanValue();  }
  • 37.
     // Displayparameters.  public void paint(Graphics g) {  g.drawString("Font name: " + fontName, 0, 10);  g.drawString("Font size: " + fontSize, 0, 26);  g.drawString("Leading: " + leading, 0, 42);  g.drawString("Account Active: " + active, 0, 58);  }  }
  • 38.
    getDocumentBase( ) and getCodeBase()  Java will allow the applet to load data from the directory holding the HTML file that started the applet (the document base ) and the directory from which the applet’s class file was loaded (the code base ).  These directories are returned as URLobjects by getDocumentBase( )and getCodeBase( ) . They can be concatenated with a string that names  the file you want to load
  • 39.
    AppletContext and showDocument() To allow your applet to transfer control to another URL, you must use the showDocument( ) method defined by the AppletContext interface. AppletContext is an interface that lets you get information from the applet’s execution environment. The context of the currently executing applet is obtained by a call to the getAppletContext()method defined byApplet.
  • 40.
    AppletContext and showDocument() Within an applet, once you have obtained the applet’s context, you can bring another document into view by calling showDocument( ). . This method has no return value and throws no exception if it fails, so use it carefully. There are two showDocument( )methods.
  • 41.
    showDocument(URL) displays the documentat the specified URL. The method showDocument(URL, String) displays the specified document at the specified location within the browser window. Valid arguments for where are “_self” (show in current frame)._parent” (show in parent frame), “ “_top” (show in topmost frame) and “_blank” (show in new browser window).
  • 42.
    The following appletdemonstrates AppletContext and showDocument( ) . Upon execution,it obtains the current applet context and uses that context to transfer control to a file called Test.html. This file must be in the same directory as the applet. Test.html can contain any valid hypertext that you like.