Creating an Java Applet

What is a Java Applet?

An applet can be defined as a simple Java program that can be embedded into a web page. Since it is embedded, the program has the feature of dynamically working alongside the web browser at the client’s disposal. A Java Applet program always has to be inside an HTML code. The distinguish applets in an HTML script, either the APPLET or the OBJECT tag is used. The main advantage of using applets in your web-based programs is that it makes the interface more interactive and intriguing.

Important features of Applets

  • All applets extend from the java.applet.Applet package so this import is a must if you are working with Applets.
  • Applet codes require a platform. It is normally an Applet viewer or a web browser. These programs cannot independently execute. The Applet viewer provided by the JDK is enough to run applet programs in any Java IDE.
  • Applets have a list of methods that are assigned various roles.
  • Rather than printing an output, an applet paints it using the drawString() method of the AWT class.

Methods of an Applet Program

  • init(): This is the very first method is an applet program and can be paralleled to a constructor. It is here where all the variables and class members are initialized.
  • start(): This is the point where program starts. While init() is only called one, start is called every time the program is accessed after reaching stop().
  • paint(): This method is called to produce an output.
  • stop(): This method is called when a web browser leaves the HTML document.
  • destroy(): This method is called when you need to permanently remove an applet from memory.

Example

import java.applet.Applet;
import java.awt.Graphics;
public class Sample extends Applet
{
public void paint (Graphics g)
{
g.drawString(“welcome”, 150, 150);
}
}

 

HTML File

<html>
<body>
<applet code = “NewTestSample.class” width = “150” height = “150”>
</applet>
</body>
</html>

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.