0% found this document useful (0 votes)
3 views

Java Applets

Java Applets are small Java programs that run inside web browsers, allowing for dynamic web content. They are executed in a sandbox for security and have a specific life cycle involving methods like init(), start(), paint(), stop(), and destroy(). However, applets have been deprecated in Java 9 and are no longer widely used due to security restrictions and the rise of alternative technologies.

Uploaded by

Kakali Das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Applets

Java Applets are small Java programs that run inside web browsers, allowing for dynamic web content. They are executed in a sandbox for security and have a specific life cycle involving methods like init(), start(), paint(), stop(), and destroy(). However, applets have been deprecated in Java 9 and are no longer widely used due to security restrictions and the rise of alternative technologies.

Uploaded by

Kakali Das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Applets

Java Applets was once a very popular feature of web applications. Java Applets were small
programs written in Java that ran inside a web browser. Learning about Applet helps us
understand how Java has evolved and how it handles graphics.
Note: java.applet package has been deprecated in Java 9 and later versions, as applets are
no longer widely used on the web.
Java Applets
A Java Applet is a Java program that runs inside a web browser. An Applet is embedded in
an HTML file using <applet> or <objects> tags. Applets are used to make the website more
dynamic and entertaining. Applets are executed in a sandbox for security, restricting access
to local system resources.
Key Points:
• Applet Basics: Every applet is a child/subclass of the java.applet.Applet class.
• Not Standalone: Applets don’t run on their own like regular Java programs.
They need a web browser or a special tool called the applet viewer (which
comes with Java).
• No main() Method: Applets don't start with main() method.
• Display Output: Applets don't use System.out.prinln() for displaying the
output, instead they use graphics methods like drawString() from the AWT
(Abstract Window ToolKit).
Java Applet Life Cycle
The below diagram demonstrates the life cycle of Java Applet:

It is important to understand the order in which the various methods shown in the above
image are called.
• When an applet begins, the following methods are called, in this sequence:
o init( )
o start( )
o paint( )
• When an applet is terminated, the following sequence of method calls takes
place:
o stop( )
o destroy( )
Let’s look more closely at these methods.
1. init( ): The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ): The start( ) method is called after init( ). It is also called to restart an applet after
it has been stopped.
Note: init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is
called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a
web page and comes back, the applet resumes execution at start( )
3. paint( ): The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
• paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called.
• The paint( ) method has one parameter of type Graphics. This parameter will
contain the graphics context, which describes the graphics environment in which
the applet is running. This context is used whenever output to the applet is
required.
• paint() is the only method among all the methods mention above (which is
parameterized).
This method is crucial for updating or redrawing the visual content of the applet.
Example:
public void paint(Graphics g)
{
// Drawing a string on the applet window
// g is an object reference of class Graphic.
g.drawString("Hello, Applet!", 50, 50);
}
Now the below Question Arises:
In the prototype of paint() method, we have created an object reference without creating its
object. But how is it possible to create object reference without creating its object?
Ans. Whenever we pass object reference in arguments then the object will be provided by
its caller itself. In this case the caller of paint() method is browser, so it will provide an
object. The same thing happens when we create a very basic program in normal Java
programs. For Example:
public static void main(String []args) {
}
Here we have created an object reference without creating its object but it still runs because
it’s caller, i.e. JVM will provide it with an object.
4. stop( ): The stop( ) method is called when a web browser leaves the HTML document
containing the applet, when it goes to another page.
For example: When stop( ) is called, the applet is probably running. You should use stop( )
to suspend threads that don’t need to run when the applet is not visible. You can restart
them when start( ) is called if the user returns to the page.
5. destroy( ): The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
Key Packages for Java Applets
• java.applet.Applet: Base class for applets.
• java.awt.Graphics: Used for drawing on the applet screen.
• java.awt: Provides GUI components and event-handling mechanisms.
Creating Hello World Applet
Let’s begin with the HelloWorld applet :
import java.applet.Applet;
import java.awt.Graphics;

// HelloWorld class extends Applet


public class HelloWorld extends Applet {

// Overriding paint() method


@Override public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}
Explanation:
1. The above java program begins with two import statements. The first import
statement imports the Applet class from applet package. Every AWT-
based(Abstract Window Toolkit) applet that you create must be a subclass
(either directly or indirectly) of Applet class. The second statement import
the Graphics class from AWT package.
2. The next line in the program declares the class HelloWorld. This class must be
declared as public because it will be accessed by code that is outside the
program. Inside HelloWorld, paint( ) is declared. This method is defined by the
AWT and must be overridden by the applet.
3. Inside paint( ) is a call to drawString( ), which is a member of
the Graphics class. This method outputs a string beginning at the specified X,Y
location. It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left
corner is location 0,0. The call to drawString( ) in the applet causes the message "Hello
World" to be displayed beginning at location 20,20.
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not
begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead,
an applet begins execution when the name of its class is passed to an applet viewer or to a
network browser.
Running the HelloWorld Applet
After you enter the source code for HelloWorld.java, compile in the same way that you
have been compiling java programs (using javac command). However, running HelloWorld
with the java command will generate an error because it is not an application.
java HelloWorld
Error: Main method not found in class HelloWorld, please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet:
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet
viewer executes your applet in a window. This is generally the fastest and
easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser
• To execute an applet in a web browser we have to write a short HTML text file
that contains a tag that loads the applet.
• We can use APPLET or OBJECT tag for this purpose
• Using APPLET, here is the HTML file that executes HelloWorld
<applet code="HelloWorld" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the
applet. The APPLET tag contains several other options. After you create this html file, you
can use it to execute the applet.
Note: Chrome and Firefox no longer supports NPAPI (technology required for Java
applets).
2. Using appletviewer
• This is the easiest way to run an applet.
• To execute HelloWorld with an applet viewer, you may also execute the HTML
file shown earlier.
• For example, if the preceding HTML file is saved with RunHelloWorld.html,
then the following command line will run HelloWorld.
appletviewer RunHelloWorld.html

3. appletviewer with Java Source File


If you include a comment at the head of your Java source code file that contains the
APPLET tag then your code is documented with a prototype of the necessary HTML
statements, and you can run your compiled applet merely by starting the applet viewer with
your Java source code file. If you use this method, the HelloWorld source file looks like
this:
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/

// HelloWorld class extends Applet


public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}

}
With this approach, first compile HelloWorld.java file and then simply run the below
command to run applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
To prove this, let’s first study what is “Status Bar” in Applet?
• Status Bar”is available in the left bottom window of an applet. To use the status
bar and write something in it, we use method showStatus() whose prototype is
public void showStatus(String)
• By default status bar shows “Applet Started”
• By default background color is white.
To prove paint() method is called again and again, here is the code:
Note: This code is with respect to Netbeans IDE.
Example:
//Code to illustrate paint
//method gets called again
//and again
import java.applet.*;

//to access showStatus()


import java.awt.*;//Graphic

//class is available in this package


import java.util.Date;

//to access Date object


public class GFG extends Applet
{
public void paint(Graphics g)
{

Date dt = new Date();


super.showStatus("Today is" + dt);
//in this line, super keyword is
// avoidable too.
}
}
Note: Here, we can see that if the screen is maximized or minimized we will get an updated
time. This shows that paint() is called again and again.
Features of Applets over HTML
• Displaying dynamic web pages of a web application.
• Playing sound files.
• Displaying documents
• Playing animations
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets:
• An applet cannot load libraries or define native methods.
• An applet cannot ordinarily read or write files on the execution host.
• An applet cannot read certain system properties.
• An applet cannot make network connections except to the host that it came from.
• An applet cannot start any program on the host that’s executing it.

Parameters passed to an applet


In this article, we will show you how to pass some parameters to an applet and how to read
those parameters in an applet to display their values in the output.

Steps to accomplish this task -:


• To pass the parameters to the Applet we need to use the param attribute
of <applet> tag.
• To retrieve a parameter's value, we need to use the getParameter() method
of Applet class.

Signature of the getParamter() method

public String getParameter(String name)


• Method takes a String argument name, which represents the name of the parameter
which was specified with the param attribute in the <applet> tag.
• Method returns the value of the name parameter(if it was defined) else null is
returned.

• Passing parameters to an applet.

o In the upcoming code, we are going to pass a few parameters like Name,
Age, Sport, Food, Fruit, Destination to the applet using param attribute in
<applet>
o Next, we will retrieve the values of these parameters
using getParameter() method of Applet class.
import java.awt.*;
import java.applet.*;

/*
<applet code="Applet8" width="400" height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination" value="California">
</applet>
*/

public class Applet8 extends Applet


{
String name;
String age;
String sport;
String food;
String fruit;
String destination;

public void init()


{
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
}

public void paint(Graphics g)


{
g.drawString("Reading parameters passed to this applet -", 20, 20);
g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60);
g.drawString("Favorite fruit -" + fruit, 20, 80);
g.drawString("Favorite food -" + food, 20, 100);
g.drawString("Favorite destination -" + name, 20, 120);
g.drawString("Favorite sport -" + sport, 20, 140);
}

Output

In order to run our applet using the appletviewer, type the following command at the
command prompt-

appletviewer Applet8.java

Where Applet8.java is the name of java file that contains the code of an applet. Right after
running the applet program using appletviewer a new applet window is displayed to us -

• Passing a parameter to an applet to set a message on its status bar.

o In the upcoming code, we are passing a parameter to the applet and setting
the message on the status bar of the applet window with the value of this
parameter.
o showStatus() method of Applet class is called to set a message on the status
bar of the applet window.

import java.awt.*;
import java.applet.*;

/*
<applet code="Applet11" width="400" height="300">
<param name="StatusBar" value="Have a good day">

*/

public class Applet11 extends Applet


{
String statusBar;

public void init()


{
statusBar= getParameter("StatusBar");
}

public void paint(Graphics g)


{
g.drawString("Reading the applet parameter to set status bar message - ", 20, 20);

//Setting a message at the status bar of our applet.


showStatus(statusBar);
g.drawString("Setting the status bar message -" + statusBar, 20, 100);
}
}

Output-

In order to run our applet using appletviewer, type the following command at the
command prompt-

appletviewer Applet11.java

Where Applet11.java is the name of java file that contains the code of an applet.

o We have passed a parameter to an applet, named StatusBar with the


value Have a good day.
o Next, we have read the value of this parameter by
calling getParameter() method and have used it to set the message at the
status bar of an applet, by calling showStatus() method of Applet class.

You might also like