Java Applet
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side. An applet like
any application program can perform arithmetic operations, display graphics, play
sounds, accept user input, create animation, and play interactive games.
Advantage of Applet
There are many advantages of applet. They are as follows:
o
Secured
Drawback of Applet
Java Applet
8. Applets are restricted from using libraries from other languages such as C
or C++.
Applets can be embed into Web pages in two ways:
Local applet Write the applet locally and embed it into Web pages requiring
no Internet connection.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
Java Applet
Begin
(Load Applet)
Born
Initialization
start ( )
Stop ( )
Running
Display
Idle
start ( )
Paint ( )
destroy ( )
Dead
Destroyed
End
Exit of Browser
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.
Java Applet
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
Applet Tag
The <APPLET> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires. Save it in the same directory as
the compiled applet.
Running the Applet
..
[ Text to be displayed in the absence of Java ]
</APPLET>
The various attributes shown inside [ ] indicate the options that can be used
when integrating an applet into a Web page. Note that the minimum required
attributes are :
4
Java Applet
CODE = AppletFileName.Class
WIDTH = pixels
HEIGHT = pixels
Table : Attributes of APPLET Tag
Attribute
CODE =
AppletFileName.class
Meaning
Specifies the name of the applet class to be loaded. That
is, the name of the already compiled .class file in which
the executable Java bytecode for the applet is stored. This
attribute must be specified.
CODEBASE =
codebase_URL
(Optional)
WIDTH= pixels
HEIGHT= pixels
Page that will be reserved for the applet.
NAME = applet_
instance_name
(Optional)
ALIGN = alignment
(Optional)
HSPACE = pixels
(Optional)
VSPACE = pixels
(Optional)
ALT = alternate_text
(Optional)
If the .class file is not in the current directory, use the codebase parameter to
specify
.
the relative path if file is on the local system, or
5
Java Applet
.
the Uniform Resource Locator (URL) of the directory containing the file if it
is on a remote computer.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Java Applet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Java Applet
Save the file as HelloJavaParam .html and then run the applet using the applet
viewer as follows:
appletviewer HelloJavaParam .html
Java Applet
Table : HTML Tags and Their Functions
Tag
<HTML>.</HTML>
Function
Signifies the beginning and end of a HTML file.
<HEAD>.</HEAD>
This tag may include details about the Web page. Usually
contains <TITLE> tag within it.
<TITLE>.</TITLE>
<BODY>.</BODY>
This tag contains the main text of the Web page. It is the
place where the <APPLET> tag is declared.
<HI>.</HI>
<H6>.<H/6>
<CENTER>.<CENTE
R>
<APPLET>.>
<APPLET>.</APPLE
T>
<PARAM>
<B><B>
Text between these tags will be displayed in bold type.
<BR>
<F>
Line break tag. This will skip a line. Does not have an end
tag.
<IMG..>
Para tag. This tag moves us to the next line and starts a
paragraph of text. No end tag is necessary.
<HR>
<A> </A>
<FONT>
.</FONT>
<!........>
We can change the color and size of the text that lies in
between <FONT> and </FONT> tags using COLOR and
SIZE attributes in thetag<FONT..>.
9
Java Applet
Any text starting with a <! Mark and ending with a > mark
is ignored by the Web browser. We may add comments
here. A comment tag may be placed anywhere in a Web
page.
10
Java Applet
Getting Input From the User
Applets treat inputs as text strings. Use TextField class of the applet package.
Once text fields are created for receiving input, type the values in the fields and
edit them.
Text Fields contain items in string form. They need to be converted to the right
form, before they are used in any computations.
Interactive input to an applet
import java.awt.*;
import java.applet.*;
public class UserIn extends Applet
{
TextField text1, text2;
Public void init ( )
{
text1 = new TextField (8);
text2 = new TextField (8);
add (text1);
add (text2);
text1.setText (O);
text2.setText (O);
Public void paint (Graphics g)
{
int x = 0, y = 0, z = 0;
String s1, s2, s;
g.drawString (Input a number in each box, 10, 50);
try
{
s1 = text1.getText ( );
x = Integer. parseInt (s1);
s2 = text2.getText ( );
y = Integer. parseInt (s2);
}
Catch (Exception ex) { }
z = x + y;
s + String.val ueOf (z) ;
g.drawString (THE SUM IS :, 10, 75);
g.drawString (s, 100, 75);
}
Public Boolean action (Event event, Object object)
{
repaint ( );
return true;
}
}
Java Applet
1. Type and save the program (.java file)
2. Compile the applet (.class file)
3. Write an HTML document (.html file)
<html>
<applet
Code = UserIn.class
Width = 300
Height = 200 >
</applet>
</html)
4. Use the appletviewer to display the results.
12
Java Applet
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
13
Java Applet
12.
13.
14.
15.
16.
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
1.
2.
3.
4.
5.
6.
14
Java Applet
7.
8.
9.
10.
11.
12.
13.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
15
Java Applet
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
}
}
try{Thread.sleep(100);}catch(Exception e){}
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the
Component class.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
16
Java Applet
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on
the button.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>
17
Java Applet
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
18
Java Applet
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>
19
Java Applet
Digital clock in Applet
Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's
see the simple example:
import
import
import
import
java.applet.*;
java.awt.*;
java.util.*;
java.text.*;
}
public void paint( Graphics g ) {
g.setColor( Color.blue );
g.drawString( timeString, 50, 50 );
}
20
Java Applet
45.
}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="DigitalClock.class" width="300" height="300">
</applet>
</body>
</html>
21
Java Applet
Analog clock in Applet
Analog clock can be created by using the Math class. Let's see the simple example:
import
import
import
import
java.applet.*;
java.awt.*;
java.util.*;
java.text.*;
22
Java Applet
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
}
}
catch (Exception e) { }
}
23
Java Applet
myapplet.html
1.
2.
3.
4.
5.
6.
<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</html>
24
Java Applet
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter(). Syntax:
1.
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
1.
2.
3.
4.
5.
6.
7.
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
25
Java Applet
Applet Communication
java.applet.AppletContext class provides the facility of communication between
applets. We provide the name of applet through the HTML file. It provides getApplet()
method that returns the object of Applet. Syntax:
1.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ContextApplet extends Applet implements ActionListener{
Button b;
public void init(){
b=new Button("Click");
b.setBounds(50,50,60,50);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
AppletContext ctx=getAppletContext();
Applet a=ctx.getApplet("app2");
a.setBackground(Color.yellow);
}
}
myapplet.html
1.
2.
3.
4.
5.
6.
7.
8.
9.
<html>
<body>
<applet code="ContextApplet.class" width="150" height="150" name="app1">
</applet>
<applet code="First.class" width="150" height="150" name="app2">
</applet>
</body>
</html>
26