Tuesday, April 10, 2012

Applets in JAVA

An applet is a Java program that runs within a Java-compatible WWW browser or
in an appletviewer. To execute your applet, the browser:

Creates an instance of your applet

• Sends messages to your applet to automatically invoke predefined lifecycle
methods

The predefined methods automatically invoked by the runtime system are:

• init(). This method takes the place of the Applet constructor and is only called
once during applet creation. Instance variables should be initialized in this method.
GUI components such as buttons and scrollbars should be added to the GUI in
this method.

• start(). This method is called once after init() and whenever your applet is
revisited by your browser, or when you deiconify your browser. This method
should be used to start animations and other threads.

• paint(Graphics g). This method is called when the applet drawing area needs
to be redrawn. Anything not drawn by contained components must be drawn in
this method. Bitmaps, for example, are drawn here, but buttons are not because
they handle their own painting.

• stop(). This method is called when you leave an applet or when you iconify
your browser. The method should be used to suspend animations and other
threads so they do not burden system resources unnecessarily. It is guaranteed to
be called before destroy().

• destroy(). This method is called when an applet terminates, for example, when
quitting the browser. Final clean-up operations such as freeing up system
resources with dispose() should be done here.

 The dispose() method of Frame
removes the menu bar. Therefore, do not forget to call super.dispose() if you
override the default behavior.

The basic structure of an applet that uses each of these predefined methods is:
import java.applet.Applet;

// include all AWT class definitions

import java.awt.*;
public class AppletTemplate extends Applet {
public void init() {
// create GUI, initialize applet
}
public void start() {
// start threads, animations etc...
}
public void paint(Graphics g) {
// draw things in g
}
public void stop() {
// suspend threads, stop animations etc...
}
public void destroy() {
// free up system resources, stop threads
}
}

No comments:

Post a Comment