0% found this document useful (0 votes)
54 views10 pages

Applet Programming

This document discusses applets in Java. It defines applets as small Java programs that can be run over the Internet in web browsers. It describes how applets can be embedded in web pages and distinguishes between local and remote applets. It also outlines the basic differences between applets and standalone applications, the lifecycle of an applet, and some standard methods used in applets like init(), start(), stop(), paint(), and destroy(). Finally, it provides an example of a simple addition applet program and uses of the standard applet methods.
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)
54 views10 pages

Applet Programming

This document discusses applets in Java. It defines applets as small Java programs that can be run over the Internet in web browsers. It describes how applets can be embedded in web pages and distinguishes between local and remote applets. It also outlines the basic differences between applets and standalone applications, the lifecycle of an applet, and some standard methods used in applets like init(), start(), stop(), paint(), and destroy(). Finally, it provides an example of a simple addition applet program and uses of the standard applet methods.
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/ 10

ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

INTRODUCTION TO APPLET
Applets are small java programs that are used in internet computing. They can be transported
over the internet from one computer to another computer and run using the appletviewer or any
web browser that supports java. Applet can be used to perform arithmetic operations, display
graphics, play sounds, accept user input, create animation and play interactive games like any
other application.
Since applets are used in internet computing. So we can embed applet into web pages in two
ways as.
 We can write our own applet and embed them into web pages
 We can download an applet form a remote computer system and embed it into the web
pages

Types of applet
Local applet
Applets developed in a local computer are known as local applet. To run local applet in local
computer, we don’t need internet. It simply searches the directories in the local system and
locates and loads the specified applet.
Remote applet
Applets which are developed by someone else and stored on a remote computer connected to the
internet are known as remote applet. To run the remote applet to the local computer, the local
system must be connected with internet. We can download remote applet onto the local computer
via internet and run it.

For example, accessing local and remote applet from the html file as shown below:
import java.awt.Graphics;
import java.applet.Applet;
public class HelloApplet extends Applet{
1
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

String message ="Welcome to Applet Programming";

public void draw(Graphics g){


g.drawString(message,100,100);
}
}
Now using html tags for remote applet,
<html>
<head>
<title>Welcome to Remote Applet!</title>
</head>
<body>
<applet name="remoteApplet"
codebase="www.sunilbist.com.np\applet\" code="HelloApplet.class" width="400"
height="400" alt="Remote Applet" align="10px" vspace="5px" hspace="5px">
</applet>
</body>
</html>

Again for the html tags for local applet,


<html>
<head>
<title>Welcome to Local Applet!</title>
</head>
<body>
<applet name="localApplet"
codebase="C:\Users\SunilBahadur\Desktop\applet\" code="HelloApplet.class"
width="400" height="400" alt="Local Applet" align="10px" vspace="5px"
hspace="5px">
</applet>
</body>
</html>

Difference between applet and application


The basic difference between applet and application (both are java program) is
 Applet don’t use the main () method for initiating the execution of the code. When the
applet is loaded, it automatically calls certain methods of applet class to start and execute
the applet code.
 Unlike stand-alone application, applets cannot be run independently. They run from
inside a web page using a special feature known as HTML tag.
 Applet cannot read from or write to the file.
 Applet cannot communicate with other server on the network
 Applet cannot run any program on the local computer.

2
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

When to use applet


 When we need something dynamic to be included in the display of a web page.
 When we require some flash output.
 When we want to create a program and make it available on the internet for use by others
on their computers

Steps To create and use an Applet


1. Building an applet code (.java file)
2. Creating an executable applet (.class file)
3. Designing a web page using HTML tags
4. Preparing an <APPLET> tag into the web page
5. Incorporating <APPLET> tag into the web page
6. Creating HTML file
7. Testing the applet code

Applet life Cycle


There are various states in every Applet which are as listed below:
1. Born state
2. Running state
3. Idle state (may or may not)
4. Dead state

3
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

1. Born State: When the class is executed, the init () function is automatically invoked. At this
stage an Applet is said to be born. This state is also called initialization state. During the applet
life cycle, the born state occurs only once. The init function is defined within an Applet. This
function is used to initialize instance members, to load the required fonts, to initialize objects, to
load pictures, to load back colors, etc.
2. Running State: After initialization, this state will automatically occur by invoking the start ()
method of applet class which again calls the run () method and which calls the paint () method.
The running state also occurs from idle state when the applet is reloaded.
3. Idle State: The idle state will make the execution of the applet to be halted temporarily.
Applet moves to this state when the currently executed applet is minimized or when the user
switches over to another page. At this point the stop () method is invoked. From the idle state the
applet can move to the running state.
4. Dead State: When the applet programs terminate, the destroy function is invoked which
makes an applet to be in dead state.

Creating an applet program


Applet is a window based application. For writing an Applet program, we need to import two
packages– java.awt.* and java.applet.*. The java.awt.* package provides a set of classes and
using those classes we can create a window component and it also contains a graphic class; the
java.applet.* package is used to use an applet class which is present in applet package.
import java.awt.*;
import java.applet.*;
public class Addition extends Applet{
int x,y,z;
String sum;
public void init(){
x = 10;
y = 20;
z = x + y;
sum = "SUM of " +x +" and "+ y + " is " +String.valueOf(z);

}
public void paint(Graphics g){
g.drawString(sum,10,30);
}
}
Now create an html code to make it runnable as,
<html>

4
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

<head>
<title>Addition Applet!</title>
</head>
<body>
<applet code="HelloApplet.class" width="400" height="400">
</applet>
</body>
</html>

Now you need to compile the java code and it will create .class file, finally goto the location
where your .class and html file saved from command prompt type: appletviewer htmlfilename
then you will see the result to the screen.

Applet Standard Methods:


Public keyword is used because we run an applet program in a media different from that in
which we write it. paint() method used in the above example calls drawString() function which
is a function of Graphics class. Applet class contains certain functions like init(), start(), stop(),
paint(), destroy(), etc. which are usually used in programs.
1. init() method: Whenever an applet is loaded into a web page this method is automatically
called. This method provides an appropriate place for initialization of the variables required and
other set up operations such as setting of background color, defining the applet’s layout, parsing
parameters, etc.
2. start() method: After the initialization is completed, start() method is called. The difference
between this method and the init() method is that init() method is called only when the page is
loaded, whereas start() method is called every time the page is loaded and every time the page is
restarted. That is, if a user navigated from one page to another page and then he returns to the
original page, start() method is called again but the init() method is not called again. This method
is mainly used while implementing threads in Java.
3. stop() method: This method is called whenever the user navigates from one page to another
page. It is always advisable to use stop() method if any type of animation or memory consuming
activities is being performed in order to avoid wasting of system resources.
4. destroy() method: This method is called immediately before the applet exits. The exiting
operation is caused by either the applet operation requesting for the exit or may be the web
browser is shut down. When it is called it directs the applet to free up all the system resources
being used by it.
5. paint() method: This method is used to draw items.

5
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Example of applet standard methods


import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;

public class EventHandlingExample extends Applet implements


MouseListener {
StringBuffer strBuffer;

public void init() {


addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}

public void start() {


addItem("starting the applet ");
}

public void stop() {


addItem("stopping the applet ");
}

public void destroy() {


addItem("unloading the applet");
}

void addItem(String word) {


System.out.println(word);
strBuffer.append(word);
repaint();
}

public void paint(Graphics g) {


//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);

//display the string inside the rectangle.


g.drawString(strBuffer.toString(), 10, 20);
}

public void mouseEntered(MouseEvent event) { }


public void mouseExited(MouseEvent event) { }
public void mousePressed(MouseEvent event) { }
public void mouseReleased(MouseEvent event) { }

public void mouseClicked(MouseEvent event) {


addItem("mouse clicked! ");
}
}

6
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Passing Parameters to Applets


Sometimes it is tedious to supply values to the running applet. The best solution is to pass
parameter from the html file. The following example show how the html file is sending
parameter and how the java code handles those parameters at runtime.
<html>
<head>
<title>An Applet Program - Passing parameters to Java applets</TITLE>
</head>
<body>
<applet code="Paramter.class" width="400" height="50">
<PARAM NAME="font" VALUE="Dialog">
<PARAM NAME="size" VALUE="24">
<PARAM NAME="string" VALUE="Hello This is me Paramter">
</applet>
</body>
</html>

Now handling the parameter from java applet code,


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

public class Paramter extends Applet {

public void paint(Graphics g) {

String myFont = getParameter("font");


String myString = getParameter("string");
int mySize = Integer.parseInt(getParameter("size"));

Font f = new Font(myFont, Font.BOLD, mySize);


g.setFont(f);
g.setColor(Color.red);
g.drawString(myString, 20, 20);
}
}
As you can see, this is a fairly simple Java applet. It retrieves the applet parameters passed to it
with the getParameter() method, then uses those parameters to construct its output. In this case
the few parameters we've passed in deal with the font and the string to be printed. In a more
elaborate example we might pass in more applet parameters to customize the applet's appearance.

Q. Write an applet program that pass name of your JAVA lecturer name from the applet
parameter tag and display in the applet screen
Soln:
<html>
<head>
<title>Java Lecturor</title>
</head>

7
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

<body>
<applet code="Parameter.class" width="400" height="200">
<param name="parName" value="Sunil Bahadur Bist">
</applet>
</body>
</html>

Now to handle the parameter send from the applet we use java applet code as:
import java.applet.*;
import java.awt.*;
public class Parameter extends Applet{
public void paint(Graphics g){
String name = getParameter("parName");
String message="Lecturor: "+name;
g.drawString(message, 20, 20);
}
}

Q. Create an applet program to count the no of click clicked by the user as shown in the figure
below:

Soln:-
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Counter extends Applet {
private TextField txtCount;
private int count = 0;

@Override
public void init() {
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
add(new Label("Counter: "));
txtCount = new TextField("0", 10);
txtCount.setEditable(false);
add(txtCount);
Button btnCount = new Button("Count");
add(btnCount);

// Handling the button-click


btnCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
++count;
8
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

txtCount.setText(count + "");
}
});
}
}

Now create an html page to display result as,


<html>
<head>
<title>Counter</title>
</head>
<body>
<applet code="Counter.class" width="250" height="100"></applet>
</body>
</html>

Q. Write an applet program to show the following screen when the user input integer the values to
the text box the output will be generated as shown in the figure:

Soln:
import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.TextField;

public class Sum extends Applet {


TextField txtN1, txtN2;
String msg ="Input Both Number and Press Enter";
public void init(){
txtN1 = new TextField(40);
txtN2 = new TextField(40);
add(txtN1);
add(txtN2);
}
public void paint(Graphics g){
int x=0, y=0,z=0;
g.drawString(msg, 25, 80);

9
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np
ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

try {
x= Integer.parseInt(txtN1.getText());
y= Integer.parseInt(txtN2.getText());

} catch (Exception e) {}
z=x+y;
g.drawString("THE SUM IS : "+String.valueOf(z), 25, 100);
}
public boolean action(Event event, Object object){
repaint();
return true;
}
}
Now design web page as shown below,

<html>
<head>
<title>User Input Addition Applet!</title>
</head>
<body>
<applet code="Sum.class" width="400" height="130"></applet>
</body>
</html>

10
Instructor: Sunil Bahadur Bist sunilbdrbist@gmail.com URL: www.sunilbist.com.np

You might also like