Search Techno Talk

Java Applet Source Code

Posted 9:53 PM by Sobia in Labels: , , ,
Java applet source code is written in the same way as Java application source code, with a text editor. The difference is that Java applets do not have a main method. Instead, they have several other methods that are called by the VM when requested by the browser. Here is the source code for the simple FilledBox applet:
import java.awt.*;
import java.applet.Applet;
/**FilledBox displays a filled, colored box in the browser window*/
public class FilledBox extends Applet {
// This variable stores the color specified in the HTML document Color boxColor;
/** Get the box color from the host HTML file*/
public void init() {
String s;
s= getParameter("color");
//The default color is gray
boxColor = Color.gray;
//We expect a parameter called color, which will have
//the value red, white, or blue. If the parameter
//is missing, s will be null
if (s !=null) {
if (s.equals("red")) boxColor=Color.red;
if (s.equals("white")) boxColor=Color.white;
if (s.equals("blue")) boxColor=Color.blue;
}
}
/**Paint the box in region assigned to the applet.
* Use the color specified in the HTML document
*/
public voic paint(Graphics g) {
g.setColor (boxColor);
g.fillRect (0, 0, size().width, size().height);
}
}
A main method is required by all Java applications; it is conspicuously absent in this applet. Java applets do not have any required methods at all. However there are five methods that the VM may call when requested by the Web browser (or appletviewer):

public void init ()
Initializes the applet Called only once.

public void start ()
Called when the browser is ready to start executing the initialized applet. Can be called multiple times if user keeps leaving and returning to the Web page. Also called when browser deiconified.

public void stop ()
Called when the browser wishes to stop executing the applet. Called whenever the user leaves the Web page. Also called when browser iconified.

public void destroy ()
Called when the browser clears the applet out of memory.

public void paint(Graphics g)
Called whenever the browser needs to redraw the applet.

If the applet does not implement any of these methods, the applet will have no functionality for the specific method not implemented. In the example, init and paint are implemented. The init function obtains the desired box color from a parameter in the host document. The paint method draws the filled box in the browser window.
Save this Java applet source as FilledBox.java.


0 comment(s) to... “Java Applet Source Code”

0 comments:

Post a Comment

Google Groups
Subscribe to Techno Talk
Email:
Visit this group