Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

Applets

Applets

Unit Structure

10.1 Introduction to Applet
10.2 Applet vs Application
10.3 Applet class
10.4 Advantages of Applet
10.5 Applet Lifecycle
10.6 My First Applet
10.7 Applet tag
10.8 Passing Parameters to Applet
10.9 Types of Applets
10.10 Examples

10.1 Introduction to Applet

There are two kinds of Java programs, applications (also called stand-alone programs) and Applets. An Applet is a small Internet-based program that has the Graphical User Interface (GUI), written in the Java programming language.
Applets are designed to run inside a web browser or in applet viewer to facilitate the user to animate the graphics, play sound, and design the GUI components such as text box, button, and radio button. When applet arrives on the client, it has limited access to resources, so that it can produce arbitary multimedia user interface and run complex computation without introducing the risk of viruses or breaching data integrity.
To create an applet, we extend the ―java.applet.Applet‖ class And by overriding the methods of java.awt.Applet, new functionality can be placed into web pages.
Applets are compiled using javac compiler and it can be executed by using an appletviewer or by embedding the class file in the HTML (Hyper Text Markup Languege) file.

10.2 Applet vs Application 

Applets as previously described, are the small programs while applications are larger programs. Applets don't have the main method while in an application execution starts with the main method. Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server. Applications are designed to exists in a secure area. while the applets are typically used. Applications are not too small to embed into a html page so that the user can view the application in your browser. On the other hand applet have the accessibility criteria of the resources.

10.3 Applet class

The java.applet package is the smallest package in Java API(Application Programming Interface). The Applet class is the only class in the package. The Applet class has many methods that are used to display images, play audio files etc but it has no main() method. Some of them were explained below that give you the knowledge about Applets and their behavior.
init() : This method is used for whatever initializations are needed for your applet. Applets can have a default constructor, but it is better to perform all initializations in the init method instead of the default constructor.
start() : This method is automatically called after Java calls the init method. If this method is overwritten, code that needs to be executed every time that the user visits the browser page that contains this applet.
stop() : This method is automatically called when the user moves off the page where the applet sits. If your applet doesn't perform animation, play audio files, or perform calculations in a thread, you don't usually need to use this method.
destroy(): Java calls this method when the browser shuts down.

10.4 Advantages of Applet

Following are the advantages of a Java Applet:

  • The most important feature of an Applet is, It is truely platform independent so there is no need of making any changes in the code for different platform i.e. it is simple to make it work on Linux, Windows and Mac OS i.e. to make it cross platform.
  • The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only.
  • It can move the work from the server to the client, making a web solution more scalable with the number of users/clients.
  • The applet naturally supports the changing user state like figure positions on the chessboard.
  • Applets improves with use: after a first applet is run, the JVM is already running and starts quickly.
  • Applets can be used to provide dynamic user-interfaces and a variety of graphical effects for web pages.

10.5 Applet Lifecycle

Every java Applet inherits a set of default behaviours from the Applet class. As a result, when an applet is loaded it undergoes a series of changes in its state. Following are the states in applets lifecycle.
1) Born or Initialisation state :
An applet begins its life when the web browser loads its classes and calls its init() method. This method is called exactly once in Applets lifecycle and is used to read applet parameters. Thus, in the init() method one should provide initialization code such as the initialization of variables.
Eg. public void init()
{
//initialisation
}
2) Running State:
Once the initialization is complete, the web browser will call the start() method in the applet. This method must called atleat once in the Applets lifecycle as the start() method can also
be called if the Applet is in ―Stoped‖ state. At this point the user can begin interacting with the applet.
Eg. public void start()
{
//Code
}
3) Stopped State:
The web browser will call the Applets stop() method, if the user moved to another web page while the applet was executing. So that the applet can take a breather while the user goes off and explores the web some more. The stop() method is called atleast once in Applets Lifecycle.
Eg. publc void stop()
{
//Code
}
4) Dead State:
Finally, if the user decides to quit the web browser, the web browser will free up system resources by killing the applet before it closes. To do so, it will call the applets destroy() method. One can override destroy() to perform one-time tasks upon program completion. for example, cleaning up threads which were started in the init() method.
Eg. public void destroy()
{
// Code
}
Note: If the user returns to the applet, the web browser will simply call the applet's start() method again and the user will be back into the program.
5) Display State :
Applet moves to the display state whenever it has to perform the output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task.
Eg. public void paint(Graphics g)
{
//Display Statements
}
One can show Lifecycle of an Applet Graphically as follows:

10.6 My First Applet

The following example is made simple enough to illustrate the essential use of Java applets through its java.applet package.
Example.
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("My First Applet",40,40);
}
}

  • Save the file as SimpleApplet.java 
  • Compile the file using javac SimpleApplet.java

Here is the illustration of the above example,

  • In the first line we imorts the Abstract Window Toolkit(AWT) classes as Applet 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. 
  • In the second line we import the Applet package, which contains the class ―Applet‖. As every applet that we create is the subclass of Applet. 
  • The next line declares the class SimpleApplet. This class must be declared in public, because it will be accessed by code that is outside the program. 
  • Inside simpleApplet, paint() method is declared. This method is defined by the AWT and must be overridden by the Applet. Method paint() is called each time that the applet must redisplay its output.
  • This paint() method has parameter of type ― Graphics‖. This parameter contains 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.
  • Inside paint() method is a call to drawstring(), which is a member of the Graphics class. This method output a String beginning at specified X, Y locations.

How to run an Applet? 

  • There are two ways in which one can run an applet, as follows

1) Executing the applet within a java-compatible web browser.
2) Using an applet viewer, such as the standard SDK tool, ―appletviewer‖. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

  • To execute an applet in a web browser, you need to write a short HTML text file that contains the appropriate APPLET tag.

For above example it is
<html>
<body>
<applet code="SimpleApplet.class" width=200 height=100>
</applet>
</body>
</html>

  • Save this code in text file with extension .html say Myapplet.html. 
  • Compile the file using javac SimpleApplet.java 
  • On successful compilation of SimpleApplet.java file, execute the this file using appletviewer Myapplet.html or just open this html file dirctly.

The output of above example appears as shown in the following figure :
OR


Insted of creating different text file for html code one can write above program as follows

import java.awt.*;
import java.applet.*;
/* <applet code="SimpleApplet" width=200 height=100>
</applet>
*/
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("My First Applet",40,40);
}
}


  • Save the file as SimpleApplet.java 
  • Compile the file using javac SimpleApplet.java 
  • On successful compilation, execute the this file using appletviewer SimpleApplet.java

The output remains same.
Building an applet code:

  • Applet code uses the series of two classes, namely Applet and Graphics from java class library.
  • Applet class which is contained in the java.applet package provides life and behavior to the applet through its methods such as init(), start(), and paint(). 
  • When an applet is loaded, java automatically calls a series of applet class methods for starting, running and stopping the applet code. 
  • The applet class therefore maintains the lifecycle of an applet. 
  • The paint() method of the applet class, when it is called, actually display the result of applet code on the screen. The output may be text, graphics or sound. The paint() method, which requires a Graphics object as an argument, is defined as follows:

public void paint(Graphics g)

  • This requires that the applet code imports the java.awt package that contains the Graphics class. 
  • All output operations of an applet are performed using the methods defined in the Graphics class.

10.7 Applet tag

The Applet tag is used to start an applet from both HTML document and form applet viewer.
An applet viewer will execute each Applet tag that it finds in a separate window, while web browsers like Netscape Navigator, Internet Explorer and HotJava will allow many applets in a single page.
The <applet....> tag included in the body section of HTML file supplies the name of the applet to be loaded and tells the browser how much space the applet ruquires
The synatax for the standard Applet tag is as follows
<applet[codebase=codebaseURL] code=‖Applet file‖
[ALT=‖alternative text]
[name=AppletInstanceName]
Width=pixels height= pixels
[align= alignment]
>
[<param name=‖Attributename‖ value =‖Attribute value‖]
[<param name=‖Attributename‖ value =‖Attribute value‖]
........
[HTML displayed in the absence of java]
</applet>

Here is meaning of each peice of above code

  • Codebase: Codebase is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for te applet‘s executable class file. The HTML document‘s URL directory is used as the CODEBASE if this attribute is not specified. 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 required attribute that gives the name of the file containing the applets compiled .class file. This file is relative t the code base URL of the applet , which is the directory that the HTML file whs in or th edirectory indicated by the CODEBASE if set. 
  • ALT : The ALT tag is an optional attribute used to specify a short text message that should be displayed if browser understand the APPLET tag but cant currently run java applet. 
  • 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. To obtain an applet by name, use getAppet(), which is defined by the AppletContext interface. 
  • Param name and Value : The PARAM tag allows us to specify applet specific arguments in an HTML page. Applets access their attributes with the getParameter() method.

10.8 Passing Parameters to Applet

One can supply user-defined parameters to an applet using <param.....> tag. Each <param....> tag has a name attribute such as color,and a value attribute such as red. Inside the applet code, the applet can refer to that parameter by name to find its value. For e.g. the color of the text can be changed to red by an applet using a <param...> tag as follows
<applet....>
<param=color value = ―red‖>
</applet>
Similarly we can change the text to be displayed by an applet by supplying new text to the applet through a <param....>tag as shown below.
<param name=text value = ―xyz‖ >
Passing a parameters to an applet is similar to passing parameters to main() method using command line arguments. To set up and handle parameters, we need to do two things.
1) Include appropriate <param.....> tags in the HTML document.
2) Provide code in the applet to pass these paraments.
Parameters are passed to an applet when it is loaded. We can define the init() method in the applet to get hold of the parameters defined in the <param> tags. This is done using the
getparameter() method, which takes one string argument representing the name of the parameter and returns a string containing the value of that parameter.

10.9 Types of Applets

As we can embed applet into web pages in two ways i.e. by writting our own applet and then embed into web pages. Or by downloading it from a remote computer system and then embed it into webpage.
An applet developed locally and stored in a local system is known as local applet. Therefore when webpage is trying to find local applet it doen not need the internet connection.
A remote applte is that which is developed by some one else and stored on a remote computer connected to the internet. If our system is connected to the internet then we can download it from remote computer and run it. In order to locate and load a remote applet, we must know the applet‘s address on the web. This address is known as Uniform Resourse locator(URL) and must be specified in applet‘s document.

10.10 Examples

Example 1 // Example to illustrate Applet Lifecycle
import java.awt.*;
import java.applet.*;
/* <applet code="AppletTest" width=200 height= 100>
</applet>
*/
public class AppletTest extends Applet
{
public void init()
{
System.out.println("Applet Initialised...");
setBackground(Color.cyan);
}
public void start()
{
System.out.println("Applet Started....");
}
public void stop()
{
System.out.println("Applet Stoppen....");
}
public void destroy()
{
System.out.println("Applet Destryoed....");
}
public void paint(Graphics g)
{
g.drawString("Applet Text",200,400);
showStatus("This is shown in Status.");
}
}

  • Save the file as AppletTest. 
  • Java Compile the file using javac AppletTest.java 
  • On successful compilation, execute the file using appletviewer AppletTest.java

The output appers as shown in following figure :

Example 2 // Example to illustrate Applet Lifecycle
import java.awt.*;
import java.applet.*;
/* <applet code="Sample" width=200 height= 100>
</applet>
*/
public class Sample extends Applet
{
String msg;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init()-";
}
public void start()
{
msg += "Inside start()-";
}
public void paint(Graphics g)
{
msg +="Inside paint()-";
g.drawString(msg,10,30);
showStatus("This is shown at status");
}
}

  • Save the file as Sample. 
  • Java Compile the file using javac Sample.java 
  • On successful compilation, execute the file using appletviewer Sample.java

The output appers as shown in following figure :

Example 3 // Example for passing 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;
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);
else
fontSize=0;
}
catch(NumberFormatException e)
{
fontSize=-1;
}
param=getParameter("leading");
try
{
if(param!=null)
leading=Float.valueOf(param).floatValue();
else
leading=0;
}
catch(NumberFormatException e)
{
leading=0;
}
param=getParameter("accountEnabled");
if (param!=null)
active =Boolean.valueOf(param).booleanValue();
}
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);
}
}

  • Save the file as ParamDemo. Java 
  • Compile the file using javac ParamDemo.java 
  • On successful compilation, execute the file using appletviewer ParamDemo.java
The output appers as shown in following figure :



Example 4 // Example for getDocumentBase() & getCodeBase()
import java.awt.*;
import java.applet.*;
import java.net.*;
/* <applet code="Bases" width=300 height= 50>
</applet>
*/
public class Bases extends Applet
{
public void paint(Graphics g)
{
String msg;
URL url= getCodeBase();
msg= "Code Base:" +url.toString();
g.drawString(msg,10,20);
url= getDocumentBase();
msg= "Document Base:" +url.toString();
g.drawString(msg,10,40);
}
}

  • Save the file as Bases. Java 
  • Compile the file using javac Bases.java 
  • On successful compilation, execute the file using appletviewer Bases.java

The output appers as shown in following figure :


No comments:

Post a Comment