Tuesday, 18 September 2018

Applet Programming


Applet Programming

Applets are small java programs that are primarily used in Internet Computing. An applet is an GUI Interface that provides look and feel as compare to console application.

Applets are not directly executable instead they should run inside a browser either embedding with HTML pages or by using applet viewer.

Applets can draw pictures on a web pages, play sounds, arithmetic calculations etc.,

Local Applets: An applet developed locally and stored in a local system is known as a local applet.
Remote Applets: An applet that's stored on another computer and which must be downloaded to your computer over the Internet.

How Applets differ from Applications

Java Application Program
Java Applet Program
  • These programs can be executed independently
  • Applets cannot be executed independently
  • It contains main() method for initiating the execution of a code
  • It does not contain main() method
  • Applications have no inherent security restrictions & can perform read/write to files in local system
  • Applets cannot read or write to the files in the local computer
  • Have no special support in HTML
  • Can be embedded in HTML pages
  • These are not restricted from using libraries from other languages such as C or C++ through native methods
  • Applets are restricted from using libraries from other languages such as C or C++

Preparing to write Applets

The steps involved in developing and testing an applet are:
  • Building an applet code
  • Creating an executable applet
  • Designing a Web Page using HTML tags
  • Preparing < Applet >Tag
  • Incorporating <Applet> tag into the web page
  • Creating HTML file
  • Testing the applet code.
Building Applet Code
The applet class which is contained in the java.applet package provides life and behaviour to the applet through its methods. When an applet is loaded, java automatically calls a series of Applet class methods for starting, running and stopping the applet code.
Applet code imports java.awt package that contains the Graphic class.

Format of an applet code:

import java.awt.*;
import java.applet.*;
----------
----------
public class <appletclassname> extends Applet
{
            ………..
            ………..
            public void paint(Graphics g)
            {
                        ………….
                        ………… // applet code
                        …………
            }
            ……….
            ……….
}

Applet Life Cycle

When an applet is loaded, it undergoes a series of changes in its state. The applet states include:

  • Born or initialization state
  • Running State
  • Idle state
  • Dead or destroyed state



Applets’ Life Cycle

Initialization State

This is achieved by calling init( ) method of Applet Class. At this stage, applet is born. In this method we may do the following such as
  • Set up initial values
  • Changing fonts
  • Setting up the colors
  • Loading images
This stage occurs only once in the applet’s life cycle.

Running State

This occurs automatically after the applet is initialized by calling the start ( ) method. Starting can also occur if the applet is already in “stopped” state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Start ( ) method may be called more than once.

Idle or Stopped State

An applet becomes idle when its stopped from running. Stopping occurs automatically when we leave the page containing running applet. We can also do so by calling the stop() method explicitly.
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 quit the applet. This state occurs only once in the applets life cycle.

Display State

Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state.

Creating an Executable Applet

import java.awt.*;
import java.applet.*;
/* <applet code=”hellojava” height=400 width=300> </applet> */
public class hellojava extends Applet
{
            public void paint(Graphics g)
            {
                        g.drawString(“Hello welcome to applets”,10,100);
            }
}
  
The first imports the Abstract Window Toolkit(AWT) classes. Applets interact with the users through the AWT. The second import statement imports the applet package, which contains the class Applet.

The next line in the program declares the class hellojava. This class must be declared as public because it will be accessed by code that is outside the program. Paint( ) is defined by AWT and must be overridden by the applet. Inside paint() there is a call to drawstring( ) which is a member of the Graphics class. This method outputs a string beginning at the specified X,Y location. It has the following general form:

void drawstring(String message, int x,int y)

After we enter the source code for hellojava, compile in the same way that you have been compiling programs. Then it produces a hellojava. class file. However running a hellojava involves a different process. Infact there are 2 ways in which you can run an applet:

  • Executing the applet within a browser
  • Using an appletviewer
Designing a Web Page

A web page is basically made up of text and HTML tags that can be interpreted by a web browser of an applet-viewer. A web page is also known as HTML page or HTML document. These pages are saved using the extension .html. HTML files should be saved in the same directory where the java applet file is saved.

A webpage is divided into 3 sections:

  • Comment section (optional)
  • Head section (Optional)
  • Body section

Comment section

This section contains comments about the web page. A comment line begins with <! and ends with >. It can be included anywhere in the web page.
            <! The text in this will be ignored by the browser >
           
Head section

This section usually contains a title for the web page.
            <head>
                        <title> Welcome </title>
            </head>
The text enclosed between <title> tags will appear in the title bar of the web page. The head section is also optional.

Body section

This section contains the entire information about the web page and its behavior.
            <body>
                        <center>
                                    <h1> welcome to java applets </h1>
                        </center>
                        <br>
<applet code=filename.class
width=size in pixels
height=size in pixels>
                        </applet>
            </body>

Applet Tag

The <APPLET…> tag supplies the name of the applet to be loaded and tells the browser how much space the applet requires.

/* <applet code=”hello.class” height=400 width=300> </applet> */

The width and height statements specify the dimensions of the display area used by the applet. This HTML code tells the browser to load the compiled Java applet hello.class.

Adding Applet to HTML file

<html>
            <head>
                        <title> Welcome </title>
            </head>
            <body>
                        <center>
                                    <h1> welcome to java applets </h1>
                        </center>
                        <applet code=filename.class
    width=size in pixels     //adding appletcode to html file
    height=size in pixels>
                        </applet>
            </body>
</html>

Running the Applet

To run an applet, we require one of the following tools:

  • Java-enabled Web Browser (such as HotJava or Netscape)
  • Java appletviewer

If we use java enabled web browser we will be able to see the entire web page containing the applet. If we use the appletviewer, we will only see the applet output.

To run our applet:

appletviewer classname.html (for executing HTML file)
appletviewer classname.java (for executing java file)

More about Applet Tag

The applet tag is used to start an applet from both an HTML document and from an appletviewer.
<APPLET
            [CODEBASE=codebase URL]
            CODE=appletfile
            [ALT=alternate text]
            [NAME=appletinstancename]
            WIDTH= pixels  HEIGHT= pixels
            [ALIGN=alignment]
            [VSPACE=pixels][HSPACE=pixels]
> 
[<PARAM NAME=AttributeName1 VALUE=AttributeValue>]
[<PARAM NAME= AttributeName2 VALUE= AttributeValue>]
…………
[HTML]
</APPLET>
Bracketed items are optional

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.

CODE             Code is a required attribute that gives the name of the file containing your applet’s compiled  .class file.

ALT    Non_Java browsers will display this text where the applet would normally go. This attribute is optional.

NAME Name is an optional attribute used to specify a name for the applet instance.  This provides inter-applet communication i.e., 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 getApplet( ) which is defined by AppletContext interface.

WIDTH AND HEIGHT   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 with possible values such as LEFT, RIGHT, TOP, BOTTOM, MIDDLE, TEXTTOP, ABSBOTTOM, ABSMIDDLE.

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  The PARAM tag allows you to specify applet specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

Passing Parameters to Applets

Applet tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter( ) method. It returns the specified parameter in the form of a String object. We can supply user-defined parameters to an applet using <PARAM..> tags. Each tag has a name and a value attribute.
To set up and handle parameters, we need to do 2 things:
·         Include appropriate <PARAM..> tags in the HTML document.
·         Provide code in the applet to parse these parameters.

Java Program: hellojava.java
import java.awt.*;
import java.applet.*;
public class hellojava extends Applet
{
String str,str1;
public void init()
{
str=getParameter("string");
str1=getParameter("color");
if(str==null)
str="java";
else
str="Hello  "+str+str1;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
D:\ >javac hellojava.java

HTML File: hellojava.html

<html>
<! parameter html file>
<head>
<title><h3>Parameter html file</h3></title>
</head>
<body>
<applet code=hellojava.class
            width=400
            height=200
            >
<param name="string" VALUE="Applet!..">
<param name = color value="red">
</applet>
</body>
</html>
D:\ >appletviewer hellojava.html

Here first the java source file should be compiled then it produces a class file then that class file should be placed in the HTML document then through applet viewer you have to execute this HTML file.

More about HTML tags

HTML stands for Hypertext Markup Language. The following are the some of the HTML tags.

Tag Names
Description
<html> </html>
The text between <html> and </html> describes the web page.

<title> </title>
The text contained in it will appear in the title bar.
<head> </head>
This include the details of the web page
<body> </body>
This tag contains the main text of the web page
<br>
Line break tag.
<p> </p>
This tag moves to the next line and start a paragraph
<a href=” “> </a>
Anchor tag used to add hyperlinks
<img src=” “>
This tag displays the image on the webpage
<h1>  </h1> to
<h6>  </h6>
Header tags. Used to display headings
<font> </font>
We can change the style,color and size of the font.



Displaying Numerical Values
In applets, we can display numerical values by first converting them into strings and then using the drawString( ) method of graphics class. We can do this easily by calling the valueOf( ) method of String class.

Filename:  parademo.java

import java.awt.*;
import java.applet.*;
public class parademo extends Applet
{
            int a;
            int b;
            int c;
            String x,y,z;
            public void init()
            {
                        a=Integer.parseInt(getParameter("a1"));
                        y=String.valueOf(a);
                        y="A="+y;
                        b=Integer.parseInt(getParameter("b1"));
                        z="B="+String.valueOf(b);
                        c=a+b;
                        x="C="+String.valueOf(c);
            }
            public void paint(Graphics g)
            {
                        g.drawString(y,10,100);
                        g.drawString(z,15,150);
                        g.drawString(x,20,200);
            }
}
Filename:  parademo.html
<html>
            <body>
                        <applet code=parademo.class
                                    height=500
                                    width=800
                                    ALIGN=TEXTTOP>
                        <param name="a1" value=10>
                        <param name="b1" value=20>
                        </applet>
            </body>
</html>

Output:
D:\>javac parademo.java
D:\>appletviewer parademo.html
Getting Input from the user.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code="textinput" width=500 height=300></applet>
public class textinput extends Applet implements ActionListener
{
            Font f=new Font("TimesRoman",Font.BOLD,30);
            TextField t1,t2;
            Button b1;
            Label l1;
            public void init()
            {
                        setBackground(Color.pink);
                        setForeground(Color.black);
                        t1=new TextField(8);
                        t2=new TextField(8);
                        b1=new Button("Ok");
                        setFont(f);
                        l1=new Label("Enter a Number");
                        add(l1);
                        add(t1);
                        add(t2);
                        add(b1);
                        b1.addActionListener(this);
            }
            public void actionPerformed(ActionEvent e)
            {
                        if(e.getSource()==b1)
                        {
                                    int n, r,rev=0;
                                    String s1;
                                    s1=t1.getText();
                                    n=Integer.parseInt(s1);
                                    while(n!=0)
                                    {
                                                r=n%10;
                                                rev=rev*10+r;
                                                n=n/10;
                                    }
                                    String x=String.valueOf(rev);
                                    t2.setText(x);
                        }
            }
}
Output:
D:\>javac textinput.java
D:\>appletviewer textinput.java