Signup/Sign In

Applet in Java

An applet is a special kind of Java program that runs in a Java enabled browser. This is the first Java program that can run over the network using the browser. Applet is typically embedded inside a web page and runs in the browser.

In other words, we can say that Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as apart of a web document.

After a user receives an applet, the applet can produce a graphical user interface. It has limited access to resources so that it can run complex computations without introducing the risk of viruses or breaching data integrity.

To create an applet, a class must class extends java.applet.Applet class.

An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-in of the Web browser or a separate runtime environment to run an applet application.

JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered important.

Lifecycle of Java Applet

Following are the stages in Applet

  1. Applet is initialized.
  2. Applet is started
  3. Applet is painted.
  4. Applet is stopped.
  5. Applet is destroyed.

life-cycle-applet


A Simple Applet

import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
  public void paint(Graphics g)
    {
      g.drawString("A simple Applet", 20, 20);
    }
}

creating simple applet


Every Applet application must import two packages - java.awt and java.applet.

java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user (either directly or indirectly) through the AWT. The AWT contains support for a window-based, graphical user interface. java.applet.* imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of Applet class.

The class in the program must be declared as public, because it will be accessed by code that is outside the program.Every Applet application must declare a paint() method. This method is defined by AWT class and must be overridden by the applet. The paint() method is called each time when an applet needs to redisplay its output. Another important thing to notice about applet application is that, execution of an applet does not begin at main() method. In fact an applet application does not have any main() method.

Advantages of Applets

  1. It takes very less response time as it works on the client side.
  2. It can be run on any browser which has JVM running in it.

Applet class

Applet class provides all necessary support for applet execution, such as initializing and destroying of applet. It also provide methods that load and display images and methods that load and play audio clips.

An Applet Skeleton

Most applets override these four methods. These four methods forms Applet lifecycle.

  • init() : init() is the first method to be called. This is where variable are initialized. This method is called only once during the runtime of applet.
  • start() : start() method is called after init(). This method is called to restart an applet after it has been stopped.
  • stop() : stop() method is called to suspend thread that does not need to run when applet is not visible.
  • destroy() : destroy() method is called when your applet needs to be removed completely from memory.

Note: The stop() method is always called before destroy() method.

Example of an Applet Skeleton

import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
 public void init()
 {
  //initialization
 }
 public void start ()
 {
  //start or resume execution
 }
 public void stop()
 {
  //suspend execution
 {
 public void destroy()
 {
  //perform shutdown activity
 }
 public void paint (Graphics g)
 {
  //display the content of window
 }
}

Example of an Applet

import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
 int height, width;
 public void init()
 {
  height = getSize().height;
  width = getSize().width;
  setName("MyApplet");
 }
 public void paint(Graphics g)
 {
  g.drawRoundRect(10, 30, 120, 120, 2, 3);
 }
}

applet example


Parameter in Applet

User-define Parameter can be applied in applet using <PARAM…> tags. Each <PARAM…> tag has a name and value attribute.

Example:

  
name = color
Value = red

Syntax:

<PARAM name = ……… Value = “………” >

In an applet code, applet can refer to a parameter by its name and then find its value.

The two most important thing to handle and set up the parameter is the <PARAM> tag in the HTML document and an applet code to parse this parameter.

init() method is used to get hold of the parameters which is defined in the <PARAM> tags. And getParameter() method is used for getting the parameters.

In Applet, Parameters are passed on applet when it is loaded.

Example:

param.java

  
import java.applet.*;
import java.awt.*;
public class param extends Applet
{
  String str;
  public void init()
  {
    str=getParameter("pname");  
    if (str == null)
    str = "Welcome to studytonight.com";
    str = "Hello " + str; 
  }   
    public void paint(Graphics g)
    {
      g.drawString(str, 200, 200);
    }
}
  

param.html

  
<html>
<applet code=param.class height=300 width=300> 
<param Name="pname" value="Welcome to studytonight.com">
</applet>
</html>
  

applet-viewer-parameter

applet-start

How to run an Applet Program

An Applet program is compiled in the same way as you have been compiling your console programs. However there are two ways to run an applet.

  • Executing the Applet within Java-compatible web browser.
  • Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes your applet in a window

For executing an Applet in an web browser, create short HTML file in the same directory. Inside body tag of the file, include the following code. (applet tag loads the Applet class)

< applet code = "MyApplet" width=400 height=400 >
< /applet >

Run the HTML file

running applet inside browser

Running Applet using Applet Viewer

To execute an Applet with an applet viewer, write short HTML file as discussed above. If you name it as run.htm, then the following command will run your applet program.

f:/>appletviewer run.htm

running applet using applet viewer


Graphics in Applet

In Applet, java.awt.Graphicsclass provides methods for using graphics.

Below are the Methods of the Graphics class.

Sr No. Methods Description
1 public abstract void drawString(String str, int x, int y) Used to draw specified string.
2 public void drawRect(int x, int y, int width, int height) Used to draw a rectangle of specified width and height.
3 public abstract void fillRect(int x, int y, int width, int height) Used to draw a rectangle with a default colourof specified width and height.
4 public abstract void drawOval(int x, int y, int width, int height) Used to draw oval of specified width and height.
5 public abstract void fillOval(int x, int y, int width, int height) Used to draw oval with a default colour of specified width and height.
6 public abstract void drawLine(int x1, int y1, int x2, int y2) Used for drawing lines between the point (x1, x1) and (x2, y2).
7 public abstract booleandrawImage(Image img, int x, int y, ImageObserver observer) Used for drawing a specified image.
8 public abstract void drawArc(int x, int y, int width, int height, intstartAngle, intarcAngle) Used for drawing a circular arc.
9 public abstract void fillArc(int x, int y, int width, int height, intstartAngle, intarcAngle) Used for filling circular arc.
10 public abstract void setColor(Color c) Used to set a colour to the object.
11 public abstract void setFont(Font font) Used to set font.

Example:

GraphicsDemo1.java

  
import java.applet.Applet;  
import java.awt.*;  
public class GraphicsDemo1 extends Applet
{    
  public void paint(Graphics g)
  {  
    g.setColor(Color.black);  
    g.drawString("Welcome to studytonight",50, 50); 
    g.setColor(Color.blue);  
    g.fillOval(170,200,30,30);  
    g.drawArc(90,150,30,30,30,270);  
    g.fillArc(270,150,30,30,0,180);  
    g.drawLine(21,31,20,300);  
    g.drawRect(70,100,30,30);  
    g.fillRect(170,100,30,30);  
    g.drawOval(70,200,30,30);  
  }  
}
  

GraphicsDemo1.html

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

graphics-demo-applet

graphics-demo-applet

Working with Images in Applet

In Applet programs, images also can be used

java.awt.Image class is used for representing an image.

java.applet, java.awt and java.awt.image are the packages which are used for event handling.

Loading an image

In Applet, images are loaded using getImage() method. This method works when the constructor of the Applet is called. It is always suggested to call the constructor in init() method.

Here are some examples:

Image image1 = getImage(getCodeBase(), "image1.gif");
Image image2 = getImage(getDocumentBase(), "image1.jpeg");
Image image3 = getImage(new URL("http://java.sun.com/graphics/image.gif"));

Displaying an image

In Applet, images are displayed using drawImage() method. This method is supplied by the Graphics object, which is passed to paint() method.

Example:

Aimage.java

  
import java.awt.*;
import java.applet.*;
public class Aimage extends Applet
{
  Image img1;
  public void init()
  {
    img1=getImage(getDocumentBase(),"icon.png");
  }
  public void paint(Graphics g)
  {
    g.drawImage(img1,100,100,this);
  }   
}
  

Aimage.html

  
<html>
<applet code=Aimage height=300 width=300>
</applet>
</html>
  

images-with-applet

studytonight-icon-applet

EventHandling in Applet

In Applet we can also perform event handling.

Below is an example of event handling which prints a message when clicked on the button.

Example:

EventAppletDemo.java

  
import java.applet.*;  
import java.awt.*;  
import java.awt.event.*;  
public class EventAppletDemo extends Applet implements ActionListener
{  
  Button b1;  
  TextField tf1;  
  public void init()
  {  
    tf1=new TextField();  
    tf1.setBounds(30,40,200,20);  
    b1=new Button("Click");  
    b1.setBounds(80,150,60,50);    
    add(b1);
    add(tf1);  
    b1.addActionListener(this);  
    setLayout(null);  
  }  
  public void actionPerformed(ActionEvent e)
  {  
    tf1.setText("Welcome to studytonight");  
  }   
}
  

Myapplet.html

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

event-handling-in-applet

applet-with-event-handling

Animation in Applet

In Applet, we can also create animations in a program using a gif image. Below is an example in which drawImage() method is used which is of Graphics class, it is used for displaying an image.

Note: Download a gif file for the below example

Example:

AnimationDemo.java

  
import java.awt.*;  
import java.applet.*;  
public class AnimationDemo extends Applet 
{  
  Image p;  
  public void init() 
  {  
    p = getImage(getDocumentBase(),"ball.gif");  
  }  
  public void paint(Graphics g) 
  {  
    for(inti=0;i<500;i++)
    {  
      g.drawImage(p, i,50, this);  
      try
      {
        Thread.sleep(100);
      }
      catch(Exception e)
      {}  
    }  
  }  
}  
  

AnimationDemo.html

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

animation-applet

JApplet class

In Java, JApplet is the public class of swing. JApplet extends the class in java.applet.Applet. JApplet generates a bytecode with the help of JVM or the Applet viewer. JApplet can be written in any programming language and then can be compiled for Java Byte code.

Example:

JAppletDemo.java

  
import java.applet.*;  
import javax.swing.*;  
import java.awt.event.*;  
public class JAppletDemo extends JApplet implements ActionListener
{  
  JButton b;  
  JTextField t;  
  public void init()
  {  
    t=new JTextField();  
    t.setBounds(30,40,220,20);  
    b=new JButton("Click");  
    b.setBounds(80,150,70,40);  
    add(b);
    add(t);  
    b.addActionListener(this);  
    setLayout(null);  
  }  
  public void actionPerformed(ActionEvent e)
  {  
    t.setText("Welcome to studytonight.com");  
  }  
}
  

JAppletDemo.html

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

jclass-applet

Painting in Applet

Below is an example of Painting using mouseDragged() method of MouseMotionListener in Applet.

Example:

PaintingDemo.java

  
import java.awt.*;  
import java.awt.event.*;  
import java.applet.*;  
public class PaintingDemo extends Applet implements MouseMotionListener
{    
  public void init()
  {  
    addMouseMotionListener(this);  
    setBackground(Color.white);  
  }  
  public void mouseDragged(MouseEvent me)
  {  
    Graphics g=getGraphics();  
    g.setColor(Color.black);  
    g.fillOval(me.getX(),me.getY(),5,5);  
  }  
  public void mouseMoved(MouseEvent me)
  {}  
} 
  

PaintingDemo.html

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

applet-painting

Analog Clock in Applet

In java, Applet can be used for creating anAnalog Clock. For creating a program for the Analog clock, java.apple, java.awt, java.util, and java.text package are imported. Date and Time functions are also used. Math functions play an important role in creating an Analog Clock. below is a program for creating anAnalog Clock.

Example:

AnalogDemo1.java

  
import java.applet.*;  
import java.awt.*;  
import java.util.*;  
import java.text.*;  

public class AnalogDemo1 extends Applet implements Runnable 
{  
int width, height;  
    Thread t = null;  
    booleanthreadSuspended;  
    int hours=0, minutes=0, seconds=0;  
    String timeString = ""; 
    public void init() 
      {   
        width = getSize().width;  
        height = getSize().height;  
        setBackground( Color.black );  
      }  
public void start() 
  {  
    if ( t == null ) 
      {  
        t = new Thread( this );  
        t.setPriority( Thread.MIN_PRIORITY );  
        threadSuspended = false;  
        t.start();  
      }  
    else 
      {  
        if ( threadSuspended ) 
          {  
            threadSuspended = false;  
            synchronized( this ) 
            {  
              notify();  
            }  
          }  
      }  
   }  

public void stop() 
{  
  threadSuspended = true;  
}  

public void run() {  
  try {  
     while (true) {  

        Calendar cal = Calendar.getInstance();  
        hours = cal.get( Calendar.HOUR_OF_DAY );  
        if ( hours> 12 ) hours -= 12;  
        minutes = cal.get( Calendar.MINUTE );  
        seconds = cal.get( Calendar.SECOND );  
        SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );  
        Date date = cal.getTime();  
        timeString = formatter.format( date );  
        if ( threadSuspended ) {  
            synchronized( this ) {  
              while ( threadSuspended ) {  
                wait();  
              }  
           }  
        }  
        repaint(); 
        t.sleep( 1000 ); 
     }  
  }  
  catch (Exception e) { }
}  

void drawHand( double angle, int radius, Graphics g ) {  
  angle -= 0.5 * Math.PI;  
  int x = (int)( radius*Math.cos(angle) );  
  int y = (int)( radius*Math.sin(angle) );  
  g.drawLine( width/2, height/2, width/2 + x, height/2 + y );  
}  

void drawWedge( double angle, int radius, Graphics g ) {  
  angle -= 0.5 * Math.PI;  
  int x = (int)( radius*Math.cos(angle) );  
  int y = (int)( radius*Math.sin(angle) );  
  angle += 2*Math.PI/3;  
  int x2 = (int)( 5*Math.cos(angle) );  
  int y2 = (int)( 5*Math.sin(angle) );  
  angle += 2*Math.PI/3;  
  int x3 = (int)( 5*Math.cos(angle) );  
  int y3 = (int)( 5*Math.sin(angle) );  
  g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );  
  g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );  
  g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );  
}  

public void paint( Graphics g ) {  
  g.setColor( Color.pink );  
  drawWedge( 2*Math.PI * hours / 12, width/5, g );  
  drawWedge( 2*Math.PI * minutes / 60, width/3, g );  
  drawHand( 2*Math.PI * seconds / 60, width/2, g );  
  g.setColor( Color.white );  
  g.drawString( timeString, 10, height-10 );  
}  
}  
  

AnalogueDemo1.html

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

analog-clock

Digital Clock in Applet

In java, Applet can be used for creating a Digital Clock. For creating a program for the digital clock, java.apple, java.awt, java.util, and java.text package are imported. Date and Time functions are also used. below is a program for creating a Digital Clock.

Example:

DigitalClockDemo1.java

  
import java.applet.*;  
import java.awt.*;  
import java.util.*;  
import java.text.*;  
public class DigitalClockDemo1 extends Applet implements Runnable 
{  
  Thread t = null;  
  int h=0, m=0, s=0;  
  String timeString = "";  
public void init() 
{  
  setBackground( Color.black);  
}  
public void start() 
{  
  t = new Thread( this );  
  t.start();  
}  
public void run() 
{  
  try 
    {  
      while (true) 
        {  
          Calendar cal = Calendar.getInstance();  
          h = cal.get( Calendar.HOUR_OF_DAY );  
          if ( h> 12 ) h -= 12;  
          m = cal.get( Calendar.MINUTE );  
          s = cal.get( Calendar.SECOND );  
          SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss");  
          Date date = cal.getTime();  
          timeString = f.format( date );  
          repaint();  
          t.sleep( 1000 );  
       }  
    }  
  catch (Exception e) { }
}  
public void paint( Graphics g ) 
  {  
    g.setColor( Color.white );  
    g.drawString( timeString, 50, 50 );  
  }  
} 
  

DigitalClockDemo1.html

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

digital-clock-applet