Applet is a window based application. We need to import two
packages for writing an applet program – java.lang.awt.* and java.lang.applet.*.
The java.lang.awt.* package provides a set of classes and using those classes
we can create a window component and it also contains a graphic class; the java.lang.applet.*
package is used as we are using an applet class which is present in applet
package.
Listing 3
import java.lang.awt.*;
import java.lang.applet.*;
public class classname extends Applet
{
public void paint(Graphics g)
{
g.drawString(String,height,width);
}
}
Public keyword is used because we run an applet program in a
media different from that in which we write it. Paint() method used in the
above example calls drawString() function which is a function of Graphics
class. Applet class contains certain functions like init(), start(), stop(),
paint(), destroy(), etc. which are usually used in programs.
init() method – Whenever an applet is loaded into a web page
this method is automatically called. This method provides an appropriate place
for initialization of the variables required and other set up operations such
as setting of background color, defining the applet’s layout, parsing
parameters, etc.
start() method – After the initialization is completed,
start() method is called. The difference between this method and the init()
method is that init() method is called only when the page is loaded, whereas
start() method is called every time the page is loaded and every time the page
is restarted. That is, if a user navigated from one page to another page and
then he returns to the original page, start() method is called again but the
init() method is not called again. This method is mainly used while
implementing threads in Java.
stop() method – This method is called whenever the user
navigates from one page to another page. It is always advisable to use stop()
method if any type of animation or memory consuming activities is being
performed in order to avoid wasting of system resources.
destroy() method – This method is called immediately before
the applet exits. The exiting operation is caused by either the applet
operation requesting for the exit or may be the web browser is shut down. When
it is called it directs the applet to free up all the system resources being
used by it.
paint() method – As mentioned earlier, this method is used
to draw items.