Introduction to JAVA Applet
Java applet is a small program transported over internet and delivered to user machine in the form of byte code is platform independent. To open java applet in browser your browser must support java for that browser has to obtain licenced from oracle. Unlike java application java applet has certain limitations like java applet cannot access data on computer this provides security that’s why applets are used in banking and other applications. They cannot be executed directly they have to be opened in java compatible web browser. Applets are used to enhance the features of HTML. Applet can respond to user input like mouse button. Applet do not have main() method. When loaded automatically calls certain methods of applet class to start and execute the applet code. Applet can play multimedia files, they can display animations. There are two types of applet one is remote applet and local applet. The applet class contain in java applet package which contain method and life cycle to applet through its method such as init(), star(), and paint(). When applet is loaded java automatically calls the applet class methods for starting running and stopping the applet code.
Simple Applet Program
public class Sample extends Applet
Public void paint()
Applet Life Cycle
- Initialization State(Born)
When applet first loaded into memory applet enters into initialization state by calling init() method now applet is born.
Syntax for init() method is as follows
Public void init()
When start() method is called applet enters into the running state. Applet enter into running state from initialization.
- Stopped State
When applet is idle it enters into stopped state .when we leave current page then applet goes into idle state. Applet can enter into stop state by calling stop() method.
- Dead State
When applet is removed from memory it is dead this happens when we close page or when we close browser. Applet can be removed from memory by calling destroy() method.
To execute an applet in a Web browser, you need to write a short HTML code in text file that contains the appropriate APPLET tag. Here is the example of HTML file that executes Myapplet:
<applet code=”Myapplet.class” width=200 height=60>
To run applet following files must be in directory
Now open the file Myapplet.HTML in java compatible web browser.
Graphics in Applet
We can draw graphics in applet using class Graphics. To draw graphics in applet we have specify X and Y coordinates. Java coordinates starts from upper left corner which is (0,0).values of coordinates are in pixels. To draw any shape in applet you have to create object of Graphics class which provides following methods.
Program to draw different shapes in applet
public class Drawing extends Applet
Public void paint(Graphics g)
g.drawRect(10,20,500,400); //draws rectangle
g.drawOval(70,50,500,500);//if height and width argument is same then it draws circle