Java-Applets

Applets

Applets are small java programs that run inside a web browser. The byte code for an applet is stored as part of a web page that is made available on a web server. When we download such a web page, the applet contained in it is also downloaded and executed by the web browser.

Applets differ from application programs. Like applications, applets are created from classes. However, applets do not have a main method as an entry point, but instead, have several methods to control specific aspects of applet execution. Let’s begin with the sample applet shown here :

import java.applet.Applet;
import java.awt.Graphics;

public class Javaapp extends Applet {
    
    public void paint(Graphics g) {
        
        g.drawString("My first Java applet!", 100, 80);
    }
}

This applet consists of two import statements. The first imports the Abstract Window Toolkit Graphics class. Because applets programs are Graphical User Interface based not console based. The AWT support the window based graphical interface. The second import statement import here Applet class. Every applet that you can create must be a subclass of Applet.

The Javaapp class extends Applet class. The class must be declared as public, because it will be accessed by code that is outside the program. The paint method is called to display the output. It has one parameter of type Graphics. The graphics object has method for graphical operations such as setting drawing colors, and drawing graphics, image, and text.

Applets have various ways of drawing, or displaying, their content. This applet, a very simple one that has only text, uses the method drawstring to display its text. After you enter the program for Javaapp compile it . There are two ways available to run an applet.

Method One

Executing the applet through HTML within a java compatible browser such as Firefox, Chrome or Internet Explorer. To execute this method, you need to write a HTML file that contains appropriate APPLET tag. Here is the HTML code that executes Javaapp applet.

<applet code="Javaapp.class" width="350" height="350"></applet>

Type the above program in notepad and save it test.html. You can execute it in your browser and load the file, which causes Javaapp to be executed. The output will look like this :


Method Two

Using an appletviewer, which is a standard JDK tool. An appletviewer executes your applet in a window.


One thought on “Java-Applets

Leave a Comment