0% found this document useful (0 votes)
22 views8 pages

Lecture 10 Applets

APPLETS

Uploaded by

Evans Masika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
22 views8 pages

Lecture 10 Applets

APPLETS

Uploaded by

Evans Masika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

APPLETS

There are two types of java programs: applets and stand-alone programs (Java applications).
An applet is a java program that runs in a java enabled web browser. To create an applet, you need to create a
class that inherits from the Applet or JApplet class. This base classes provides a number of useful methods.

Differences between applets and applications:


1. An applet is a Java program that is intended to be transported over the web and executed using a web
browser i.e. it is dynamically downloaded from the web server to a browser.
2. The init method is used for all initialization processes in applets as compared to application which use
constructors.
3. An applet does not have the main method. When a web page containing an applet is loaded, it starts the
applet by calling the init method. Free standing applications must have the main method.

Benefits of Applets
i). Easy to deploy (“web components”)
ii). No need for installation or upgrades
iii). Provide more sophisticated functionality than a web page/form
iv). Allow for proprietary client-server protocols
v). Re-use code from traditional applications
vi). Very secure

Applets, web browser and server


A web browser is an application that allow users to retrieve information from remote sites on the internet
[WWW] using uniform resource locators [URLs]. A browser must incorporate the java virtual machine for it to
run java programs. The applet tag causes the virtual machine to be used to run the class code loaded from the
same URL as the HTML page or some other specified location. Applets are stored on a web server, similar to
web pages. When an applet is referred to in a web page that has been fetched and processed by a browser, the
browser generates a request to fetch (or download) the applet program, then executes the applet program in the
browser’s execution context on the client host.

HTML
Hypertext Markup Language (HTML) is the core technology that controls what Web browsers displays on
screen. Generally, HTML are documents containing both basic formatting commands (known as markup) and
links to other information (known as hypertext or hyperlinks).

HTML Tags
HTML tags(commands) have the following form: <name_of_tag>...</name_of_tag>
<html> is the first tag of any HTML page. It indicates that the contents of the page is in HTML. HTML files
are plain text files created with any text editor. Every HTML document consists of two parts: head and body

Outline of a Basic Page


<HTML> begin an HTML document
<HEAD> begin the document's header (title usually goes here)
</HEAD> end of document's header
<BODY> begin stuff that will appear in the main window of the browser blank lines are ignored - use
them to make code more readable (body of html document: html commands, text, applets, etc.)
</BODY> end of the main window of browser
</HTML> end the HTML document

Note: HTML is not case sensitive, i.e. tags can be in upper or lower case letters or even mixtures of cases

Java Programming Page 1 of 8


Deploying Applets
Applets are embedded into web pages with the <applet> tag i.e. it instructs the browser to display an applet in
that location of the web page

Syntax:
<APPLET [CODEBASE = applet_url] CODE="Name_Of_.class_File" WIDTH=Integer HEIGHT=Integer>
</APPLET>

The applet tag can be used to set several properties about the applet: - the class to load and run as an applet,
height and width, and location of class files (codebase)

Writing Applets
Writing applet involves creating a sub-class of java.applet.Applet, or javax.swing.JApplet i.e. JApplet is a top-
level Swing container hence can add usual Swing components

Example 1
import java.applet.*;
import java.awt.*;

/**
* The Hello class implements an applet that
* simply displays "Hello World!".
*/
public class Hello extends Applet {
public void init() {
}
public void paint (Graphics g) {
// Display "Hello World!"
g.drawString("Hello world!", 0, 10);
}
}

<HTML>
<HEAD>
<TITLE>A Simple Program</TITLE>
</HEAD>
<BODY>
<h1>Here is the output of my program :</h1>
<APPLET CODE=Hello WIDTH=1500 HEIGHT=250>
</APPLET>
</BODY>
</HTML>

The paint method is used to paint the screen (draw graphics) and it takes Graphics object g as a parameter as
shown below:
public void paint(Graphics g)
You need to call methods of object g to draw on an applet
g.drawString("String to draw", x, y);

This statement draws "String to draw" at location (x, y)


 (0, 0) is upper left corner of screen
 Measured in pixels (picture elements)

Java Programming Page 2 of 8


You need import java.awt.Graphics, in order to create the Graphics object

Running Applets Programs


 Use the appletviewer in an integrated Java development environment.
 Executes when HTML document containing applet is opened. The normal way to run an applet is from
an HTML document.
 There are many IDE that provide handy tools to write, compile, run and debug Java programs. Usually
they will automatically create an applet viewer if you run an applet

Tip for development/debugging:


Use the appletviewer tool for viewing and testing applets i.e it is easier to control than in a browser

The Applet Class


The Applet class provides the essential framework that enables applets to be run from a Web browser.
While every Java application has a main method that is executed, when the application starts, applets do not
have a main method. Instead they depend on the browser to call the methods in the Applet class. Every applet
is a subclass of java.applet.Applet, as outlined below:
public class MyApplet extends java.applet.Applet {
...
/** The no-arg constructor is called by the browser when the Web
* page containing this applet is initially loaded, or reloaded
*/
public MyApplet() {
...
}
/** Called by the browser after the applet is loaded
*/
public void init() {
...
}
/** Called by the browser after the init() method, or
* every time the Web page is visited
*/
public void start() {
...
}
/** Called by the browser when the page containing this
* applet becomes inactive
*/
public void stop() {
...
}
/** Called by the browser when the Web browser exits */
public void destroy() {
...
}
/** Other methods if necessary... */
}

Java Programming Page 3 of 8


When the applet is loaded, the Web browser creates an instance of the applet by invoking the applet's no-
argument constructor. Generally, a browser is a ‘container’ that provides services to the applet i.e. it drives the
applet through life-cycle methods. The browser uses the init, start, stop, and destroy methods to control the
applet. By default, these methods do nothing. To perform specific functions, they need to be modified in the
user's applet so that the browser can call your code properly. The applet must have a no-argument constructor
declared either explicitly or implicitly.
The following is descriptions of the four applet methods that correspond to the four types of reactions [initialize,
start, stop and final clean up].
1. void init () is used to initialize the applet each time it's loaded (or reloaded). It is intended for whatever
initialization is needed for an applet. Applets do not normally use constructors but they do use the init()
method for similar purposes. Commonly used to initialize variables.
2. void start () is used to start the applet's execution, such as when the applet's loaded or when the user revisits
a page that contains the applet.
3. void stop() is used to stop the applet's execution, such as when the user leaves the applet's page or quits the
browser. Therefore, the start() and stop() methods may be called multiple times during the life cycle of the
applet.
4. void destroy () is used to perform a final cleanup in preparation for unloading. The stop() method is
invoked before destroy().
The following is a diagram that shows how the browser calls these methods:
init()

Initialised

start()

Running

stop() start()

Stopped

destroy()

Destroyed

Note: Every applet needs to implement one or more of the init(), the start( ) and the paint( ) methods and are
called automatically for all applets

Drawing shapes in an applet


Java provides methods for drawing the following shapes: lines, ovals and circles, rectangles and squares, and
arcs including semicircles

Example
The code below is for the program shapes .java which illustrates how shapes are drawn in java programs
import java .awt.*;
import java .applet.*;
public class DrawShapes extends Applet{
public void paint (Graphics g){
//Displays a string.
g.drawString("Below are some shapes",20,20);
//sets applets background color to yellow.

Java Programming Page 4 of 8


setBackground(Color.yellow);
//sets the outline and fill color for the drawings.
g.setColor(Color.red);
// draws a rectangle
g.drawRect(30,30,80,40);
//Draws an oval shape
g.drawOval(120,30,80,40);
//Draws a rectangle filled with the color red.
g.fillRect(30,80,80,40);
//Draws a circle filled with the color red.
g.fillOval(120,80,80,40);
//Draws a line
g.drawLine(30,130,110,170);
//Draws an arc
g.drawArc(120,130,80,40,90,120);
//Draws an arc filled with color red.
g.fillArc(30,180,80,40,90,120);
}
}

Associated HTML file

<HTML>
<HEAD>
<TITLE>A Sample Program</TITLE>
</HEAD>
<BODY>
<h1>Here is the output of my program :</h1>
<APPLET CODE=DrawShapes WIDTH=400 HEIGHT=300>
</APPLET>
</BODY>
</HTML>

Output

Java Programming Page 5 of 8


Parameters outline
g.drawShape/fillShape(int 1,int 2,int 3,int 4,int 6,int 7);
 int 1 and 2 indicate the horizontal and vertical position of the top left corner of the rectangle
and the rectangle containing ovals, arcs and the starting point of a line.
 int 3 and 4 indicate the width and the height of the rectangle and the rectangle containing
ovals, arcs and the last point of a line.
 int 6 and 7 indicate the starting point of an arc and the total angle of the arc respectively.

The JApplet Class


The Applet class uses AWT class and is not designed to work with Swing components. To use Swing
components in Java applets, it is necessary to create a Java applet that extends javax.swing.JApplet, which is a
subclass of java.applet.Applet. JApplet inherits all the methods from the Applet class. In addition, it provides
support for laying out Swing components. To add a component to an applet, you add it to the content pane of an
applet. By default, the content pane of JApplet uses BorderLayout.

Example
import javax.swing.*;
public class WelcomeApplet extends JApplet {
public void init() {
add(new JLabel("Welcome to Java", JLabel.CENTER));
}
}

Applets and GUI components


Unlike in applications the components added to the applet are initialized within the init method. The window
listener interface is no longer needed since there is no window to be closed. We also change the way the button
listener is added. Instead of using an anonymous class, we simply add the applet itself to the button, since it
implements the action listener interface.

Example
The following is an applet and associated HTML document that would produce the output shown below when
rendered by the browser.

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

Java Programming Page 6 of 8


import java.awt.event.*;
public class GraphicalDisplay extends Applet implements
ActionListener,ItemListener{
private Label name;
private TextField txtName;
private Label gender;
private CheckboxGroup g;
private Checkbox male,female,sec,grad,postg;
private Label address;
private TextArea txaAddress;
private Label age;
private List lstAge;
private Label eduLevel;
private Button close;
public void init ( ) {
setBackground(Color.yellow);
setLayout(new FlowLayout());
name=new Label("Name");
add(name);
txtName=new TextField(20);
add(txtName);
gender=new Label("Gender");
add(gender);
g=new CheckboxGroup();
male=new Checkbox("Male",g,true);
add(male);
male.addItemListener(this);
female=new Checkbox("Female",g,false);
add(female);
female.addItemListener(this);
address=new Label("Address");
add(address);
txaAddress=new TextArea(5,20);
add(txaAddress);
age=new Label("Age");
add(age);
lstAge=new List(3,false);
lstAge.add("Below 20");
lstAge.add("Between 20 and 30");
lstAge.add("Above 30");
add(lstAge);
eduLevel=new Label("Education Level");
add(eduLevel);
sec= new Checkbox("Secondary");
add(sec);
sec.addItemListener(this);
grad= new Checkbox("Graduate");
add(grad);
grad.addItemListener(this);
postg= new Checkbox("Post Graduate");
add(postg);
postg.addItemListener(this);

Java Programming Page 7 of 8


close=new Button("Close");
add(close);
close.addActionListener( this);
}
public void itemStateChanged(ItemEvent e){}
public void actionPerformed(ActionEvent e){}
}

Associated HTML file

<HTML>
<HEAD>
<TITLE>A Simple Program</TITLE>
</HEAD>
<BODY>
<h1>Here is the output of my program :</h1>
<APPLET CODE=GraphicalDisplay WIDTH=240 HEIGHT=300>
</APPLET>
</BODY>
</HTML>

Java Programming Page 8 of 8

You might also like