Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 2 - Applates

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

CHAPTER TWO

BASICS of JAVA APPLETS

An applet is a Java program that runs in a Web browser. It can be a fully functional Java
application because it has the entire Java API at its disposal. 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.

There are some important differences between an applet and a standalone Java application,
including the following: -
− An applet is a Java class that extends the java.applet.Applet class.
− A main () method is not invoked on an applet, and an applet class will not define main().
− Applets are designed to be embedded within an HTML page.
− When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
− A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser
or a separate runtime environment.
− The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
− Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
− Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Advantage of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Operating System etc.

Drawback of Applet
• Plugin is required at client browser to execute applet.

Java Programming Chapter 2: Java Applet


Hierarchy of Applet

The AWT allows us to use various graphical components. When we start writing any applet
program we essentially import two packages namely – java.awt and java.applet.

The java.applet package contains a class Applet which uses various interfaces such as
AppletContext, AppletStub and AudioCIip. The applet class is an extension of Panel class
belonging to java.awt package.

To create a user-friendly graphical interface, we need to place various components on GUI


window. There is a component class from java.awt package which derives several classes for
components. These classed include Check box, Choice, List, buttons and so on. The Component
class in java.awt is an abstract class.

The class hierarchy for Applets is as shown in Fig

Applet class extends Panel. Panel class extends Container which is the subclass of Component.

Java Programming Chapter 2: Java Applet


LIFECYCLE OF JAVA APPLET
The java applet life cycle is managed and operated by a Java Plug-in software. The java applet
has five different life cycles. These are: -
1. Applet is initialized.

2. Applet is started.

3. Applet is painted.

4. Applet is stopped.

5. Applet is destroyed.

Life Cycle of an Applet፡ Four methods in the Applet class gives you the framework on which
you build any serious applet −
− init: This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
− start: This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
− stop: This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
− destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources behind
after a user leaves the page that contains the applet.
− paint: Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.

Lifecycle methods for Applet:


− The java.applet.Applet class five life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
− public void init(): is used to initialized the Applet. It is invoked only once.
Java Programming Chapter 2: Java Applet
− public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
− public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
− public void destroy(): is used to destroy the Applet. It is invoked only once.

➢ java.awt.Component class
The Component class provides 1 life cycle method of applet.
− 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.

Run an Applet Program


Applets can be executed in two ways: from Browser or from Appletviewer. The JDK provides
the Appletviewer utility. Browsers allow many applets on a single page, whereas applet viewers
show the applets in separate windows. There are two ways to run an applet
− By html file.
− By appletViewer tool (for testing purpose).
Example:

Note: class must be public because its object is created by Java Plugin software that resides on
the browser.

Java Programming Chapter 2: Java Applet


Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is
not required but it is for testing purpose only.

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac HelloApplet.java
c:\>appletviewer HelloApplet.java

DISPLAYING GRAPHICS IN APPLET


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
− public abstract void drawString(String str, int x, int y):
➢ is used to draw the specified string.
− public void drawRect(int x, int y, int width, int height):
➢ draws a rectangle with the specified width and height.
− public abstract void fillRect(int x, int y, int width, int height):
➢ is used to fill rectangle with the default color and specified width and height.
− public abstract void drawOval(int x, int y, int width, int height):
➢ is used to draw oval with the specified width and height.
− public abstract void fillOval(int x, int y, int width, int height):
➢ is used to fill oval with the default color and specified width and height.
− public abstract void drawLine(int x1, int y1, int x2, int y2):

Java Programming Chapter 2: Java Applet


➢ is used to draw line between the points(x1, y1) and (x2, y2).
− public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
➢ is used draw the specified image.
− public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle):
➢ is used draw a circular or elliptical arc.
− public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle):
➢ is used to fill a circular or elliptical arc.
− public abstract void setColor(Color c):
➢ is used to set the graphics current color to the specified color.
− public abstract void setFont(Font font):
➢ is used to set the graphics current font to the specified font.

DISPLAYING IMAGE IN APPLET


Applet is mostly used in games and animation. For this purpose, image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:

− public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:
public Image getImage(URL u, String image){
----
----
}

Other required methods of Applet class to display image:

− public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
− public URL getCodeBase(): is used to return the base URL.

Java Programming Chapter 2: Java Applet


Example: of displaying image in applet:
import java.awt.*;
import java.applet.*;

public class DisplayImage extends Applet {


Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sn.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

Animation in Applet
− Applet is mostly used in games and animation. For this purpose, image is required to be
moved.
Example of animation in applet:
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){}
}
}
}

The html File

Java Programming Chapter 2: Java Applet


<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

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.

Example of EventHandling in applet:


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");
}
}
To run the above applet code we can use the following Html cod
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>

Java Programming Chapter 2: 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.

Example of EventHandling in JApplet:


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
<html>
Java Programming Chapter 2: Java Applet
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.

Example of Painting in Applet:


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
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>

Java Programming Chapter 2: 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:
public String getParameter(String parameterName)

Example of using parameter in Applet:


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
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

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:
public Applet getApplet(String name){}

Example of Applet Communication


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ContextApplet extends Applet implements ActionListener{
Button b;

public void init(){

Java Programming Chapter 2: Java Applet


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
<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>

Java Programming Chapter 2: Java Applet

You might also like