Thursday 9 February 2012

Applets

Applet
An applet is a Java program that runs in a Web browser.

An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.

An APPLET usually consists of two sections:
 init() 
 paint()

 init() is short for initialization, and it is used to take care of anything that needs to be set up as an applet first runs. The paint() block is used to display anything that should be displayed.

Here is a simple example of Applet:


import java.applet.*;
import java.awt.*;
/*
<applet code="HelloWorldApplet" width="500" height="400"></applet>
*/

public class HelloWorldApplet extends Applet{
   public void paint (Graphics g)
   {
      g.drawString ("Hello World", 25, 50);
   }
}


HOW TO COMPILE AND RUN AN APPLET:

Save as:          HelloWorldApplet.java
Compile as:    javac HelloWorldApplet.java
Run as:           appletviewer HelloWorldApplet.java

NOTE:    The class must be declared   public.

Components that can be used with Applet:
Button
TextField
Label
TextArea
Choice
List
Frame


Using Listeners with Applets:

Here is an example to show the response to a button click.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="ActionListenerApplet" width="500" height="400"></applet>
*/

public class ActionListenerApplet extends Applet implements ActionListener{
String str="Hello";
Button b;public void start()
{
b = new Button("CLICK");b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae)
{
str="hiiiiii";
repaint();
}

   public void paint (Graphics g)
   {
      g.drawString (str, 25, 50);
   }
}

:::::::::::::::::::::::::::::::::::::::::::::::::::::::
Another example to show the use of event listeners:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="ActionListenerApplet2" width="500" height="400"></applet>
*/

public class ActionListenerApplet2 extends Applet implements ActionListener{
int i=1;
String str="Hello   "+i;
Button b;public void start()
{
b = new Button("CLICK");b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae)
{
i++;
str="hiiiiii    "+i;
repaint();
}

   public void paint (Graphics g)
   {
      g.drawString (str, 25, 50);
   }
}

// Here,  'i'  increments with every button click.

JAVA Project Specifications Lecture Notes: SE OS JAVA

X