Skip to content

Chapter 5 : Applets

Saket Khopkar edited this page Jan 11, 2022 · 4 revisions

Introduction:

  • Applets are small Java programs that are mainly used in Internet computing.
  • Applets can be transported over Internet from one computer to another and run using Applet Viewer or any Web Browser that supports Java.
  • Applet can do many things like arithmetic operations, display graphics, play sounds, accept user input, create animation and play interactive games.
  • Java Applets revolutionized the way Internet users retrieve and use documents on WWW. It enabled them to create and use fully interactive multimedia Web Documents. A web page can now contain not only a simple text or a static image but also a java applet which, when run, can produce graphics, sounds and moving images.
  • Java Applets therefore have begun to make a significant impact on the WWW.
Applet Application
Applets do not use main () method for initiating the execution of code. Applications use main () method for initiating the execution of code.
Applets cannot be run independently. They run inside the web page using HTML tag. Stand alone application can run independently.
Applets cannot read or write files in the local computer. Applications can read or write files in the local computer.
Applets cannot communicate with other servers on the network. Applications can communicate with other servers on the network.
Applet cannot run any program from local computer. Application can run any program from local computer.
Applets cannot use libraries from other languages such as C and C++. Applications can use libraries from other languages such as C and C++.
Applets are designed to perform small tasks and it is not full-featured application programs. Applications are full-featured programs.
Applets are mainly use for Internet computing. Applications are mainly use for standalone computing.

Steps To Develop And Test Applets:

  1. Building an Applet code (.java file)

  2. Creating an executable Applet (.class file)

  3. Designing a web page using HTML tags

  4. Preparing tag

  5. Incorporating tag into web page

  6. Creating HTML file

  7. Testing the applet code / Run Applet

  8. Building An Applet Code (.java file):

import java.awt.*; 
import java.applet.*; 
--------------- 
--------------- 
public class AppletClassName extends Applet 
{ 
    --------------- 
    --------------- 
    public void paint (Graphics g) 
    { 
        --------------- // Applet operations code --------------- 
    } 
}
// Example: 
import java.awt.*; 
import java.applet.*; 
public class HelloJava extends Applet 
{ 
    public void paint (Graphics g) 
    { 
        g.drawString (“Hello Java”, 10,100); 
    } 
}
  1. Creating an executable Applet (.class file): It is obtained by compiling the source code. Above HelloJava.java source code file can be compile as follows:
  • Move to directory containing source code and type: javac HelloJava.java
  • Compiled HelloJava.class file is placed in the same directory as the source.
  • If error message received, then we must check and correct errors and compile Applet again.
  1. Designing a web page using HTML tags:
  • We need to create web page that reference the Applet. Web page has three major sections.
  1. Preparing tag:
  • <Applet code=HelloJava.class width=400 height=200> </Applet>
  • This HTML code tells the browser to load the compiled Java applet HeloJava.class, which is in the same directory as the HTML File. And also specifies the display area for the Applet output as 400 pixels width and 200 pixels height.
  1. Incorporating tag into web page:
<HTML> 
    <HEAD> 
        <TITLE> Welcome To Java Applet </TITLE>
    </HEAD> 
    <BODY> 
        <Applet code=HelloJava.class width=400 height=200> </Applet> 
    </BODY> 
<HTML>
  1. Creating HTML file:
  • Name this file as HelloJava.html and save in the same directory as the compiled Applet.
  1. Run Applet:
  • We are having three files:
  1. HelloJava.java Source Code
  2. HelloJava.class Byte Code
  3. HelloJava.html Web Page File
  • To run applet we require either Java Enabled Web Browser or Java Applet viewer.
  • To Run Applet Type: appletviewer HelloJava.html

Applet Skeleton / Structure:

  • Most Applets override a set of methods that provides the basic mechanism to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ) are defined by Applet.
  • Another, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided.
  • Applets do not need to override those methods which they do not use.
// These five methods can be assembled into the skeleton shown here:  
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 
    }
    // Called when the applet is stopped. 
    public void stop() 
    { 
        // suspends execution 
    }
    /* Called when applet is terminated. This is the last method executed. */ 
    public void destroy() 
    { 
        // perform shutdown activities 
    }
    // Called when an applet's window must be restored. 
    public void paint(Graphics g) 
    { 
        // redisplay contents of window 
   } 
}

Applet Life Cycle:

  1. Born or Initialization State: Applets enters the initialization state when it is first loaded. It is achieved by init() method of Applet class. Then applet is born.
  2. Running State: Applet enters the running state when the system calls the start() method of Applet class. This occurs automatically after the applet is initialized.
  3. Idle State: An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. This is achieved by calling the stop() method explicitly.
  4. Dead State: An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when we want to quit the browser.

Applet Life Cycle Methods / Applet Initialization and Termination:

  • 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( )

init( ):

  • It is the first method to be called. Here we should initialize variables. This method is called only once during the run time of applet.
public void init() 
{ 
Method body 
}

start( ):

  • It is called after init( ). It is also called to restart an applet. Whereas init( ) is called only once. start( ) is called each time an applet is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).
public void start() 
{ 
Method body 
}

paint( ):

  • It is called each time our applet’s output must be redrawn. 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.
public void paint(Graphics g) 
{ 
Method body 
}

stop( ):

  • It is called when a web browser leaves the HTML document containing the applet or when it goes to another page. We should use stop( ) to suspend threads that don’t need to run when the applet is not visible. We can restart them when start( ) is called if the user returns to the page.
public void stop() 
{ 
Method body 
}

destroy( ):

  • The destroy( ) method is called when applet needs to be removed completely from memory. At this point, we should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).
public void destroy() 
{ 
Method body 
}

More About Applet Tag / Full Form Syntax of Applet Tag:

< 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>]
 . . . 
[HTML Displayed in the absence of Java] 
</APPLET>
  • CODEBASE :- Specifies the URL of the directory in which the applet is stored. If applet is stored in the same directory as the HTML file, then CODEBASE will be ommitted.
  • CODE :- Specifies the name of the applet class to be loaded. It is the name of already compiled .class file in which the executable Java bytecode for the applet is stored.
  • ALT :- Specifies a short text message that should be displayed if the browser understands the APPLET tag but can’t currently run Java applets.
  • NAME :- Specifies a name for the applet. Applets must be named so other applets on the same page can find and communicate with them. To obtain an applet by name, use getApplet( ) method.
  • WIDTH and HEIGHT :- Specifies the size (in pixels) of the applet display area.
  • ALIGN :- Specifies the alignment of the applet. Possible alignment values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
  • VSPACE and HSPACE :- VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.
  • PARAM NAME and VALUE :- Specifies applet specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

Using Fonts In Applet:

  • Font determines look of the text when it is painted. Font is used when painting on a Graphics context. Font has three properties that contribute the appearance of the text. Family Name : Specifies general name of the Font.
  1. (ex: Courier) Logical Name: Specifies the category of the Font.
  2. (ex: Monospaced) Face Name : Specifies specific Font.
  3. (ex: Courier Italic)
  • Font Constructor To Create Font: Font(String name, int style, int size)
  1. Font Name (Logical Name): Java environment support Dialog, DialogInput, Serif, Sans Serif, Monospaced and Symbol fonts. Dialog is a default font used by applet.
  2. Font Style: Font.PLAIN Font.BOLD Font. ITALIC Font.BOLD | Font. ITALIC Font Size: It specifies font size in points.
  • Example:
Font f = new Font(“Dialog”, Font.BOLD, 15);
setFont(f);
Method Description
string getFamily() Returns the family name of this Font. Ex: Courier
static Font getFont(String property) Returns a Font object from the system properties list.
String getFontName() Returns the font face name of this Font. Ex: Courier Italic
int getSize() Returns the point size of this Font, rounded to an integer
int getStyle() Returns the style of this Font. Ex: PLAIN, BOLD, ITALIC
boolean isBold() Indicates whether or not this Font object's style is BOLD.
boolean isItalic() Indicates whether or not this Font object's style is ITALIC.
boolean isPlain() Indicates whether or not this Font object's style is PLAIN.
int hashCode() Returns a hash code for this Font. It is unique code.
boolean equals(Object obj) Compares this Font object to the specified Object. If it match, return true otherwise false.