Thursday, October 21, 2010

Introducing Java applet tutorial with examples

What is Applet?
Applet is a small application that are accessed on an internet server,transported over the internet,automatically installed and run as part of a web document.
Security by applet:
After an applet arrives on the client,it has limited access to resources so thatit can produce a GUI and run complex computation without introducing the risk of viruses or breaching data integrity.
Starting Applet
There are two varieties of Applets.One that uses AWT to provide GUI,and second that uses SWINGS for GUI.
   All applets are subclasses of Applet.Applet is not standalone it runs on web browser or on Appletviewer.  (See ROBOT Class in java)
appletviewer is provided by JDK.

Applet will not have main()(but few Applets have main()).
A sample example:

import java.awt.*;                               //import awt package
import java.applet.*;
/*
<applet code="Apple" width="200" height="300">
</applet>
*/
public class Apple extends Applet
{
String msg;
public void init(){
setBackground(Color.green);
setForeground(Color.red);
msg="Inside init()--";
}
public void paint(Graphics g){
g.drawString("A Simple Applet",20,20);
msg+="Inside paint()--";
g.drawString(msg,200,200);
}
}
Now compile and then run using this command-->appletviewer Apple.java
than a window appears.
Explanation:
                      code inserted in /*<applet>------</applet>*/  when applet viewer encounters this tag it displays the applet.
Applet starts with init()-------->start()------->stop()(or destroy).
Insert those things which needs ti be started only once in init().
and main program in start().
   paint() do draw any thing(image,String).
It takes parameter Graphics and drawString() is a method.

Note:
           You can also use <object> tag but sun recommends to use <applet>. Width and height should  be included.

See Java program to Applet Banner
 

No comments:

Post a Comment

Post a Comment