English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I)/O)

Java Reader/Writer

Other Java topics

Java Applet Basics

An Applet is a Java program. It generally runs within a web browser that supports Java. Because it has complete Java API support, Applet is a fully functional Java application.

The following shows the important differences between independent Java applications and applet programs as shown:

  • The Applet class in Java inherits from the java.applet.Applet class.

  • The Applet class does not define main(), so an Applet program does not call the main() method.

  • Applets are designed to be embedded in an HTML page.

  • When the user browses an HTML page containing an Applet, the Applet's code is downloaded to the user's machine.

  • To view an Applet, you need JVM. JVM can be a plugin for a web browser or a standalone runtime environment.

  • The JVM on the user's machine creates an instance of the Applet class and calls various methods in the Applet lifecycle.

  • Applets have strict security rules enforced by web browsers, and the security mechanism of Applets is called sandbox security.

  • Other classes needed by Applets can be downloaded in the form of Java Archive (JAR) files.

Applet lifecycle

The four methods in the Applet class provide a framework on which you can develop small applications:

  • init: The purpose of this method is to provide any necessary initialization for your Applet. This method is called after the param tags within the Applet tag are processed.

  • start: This method is automatically called after the browser calls the init method. This method is called every time the user returns to the page containing the Applet from another page.

  • stop: This method is automatically called when the user removes the Applet from the page. Therefore, this method can be called repeatedly in the same Applet.

  • destroy: This method is only called when the browser is closed normally. Since Applets are only valid on HTML web pages, you should not leave any resources behind when the user leaves the page containing the Applet.

  • paint: This method is called immediately after the start() method, or when the Applet needs to be redrawn in the browser. The paint() method actually inherits from java.awt.

"Hello, World" Applet:

Below is a simple Applet program HelloWorldApplet.java:

import java.applet.*;
import java.awt.*;
 
public class HelloWorldApplet extends Applet
{
   public void paint(Graphics g)
   {
      g.drawString("Hello World", 25, 50);
   }
}

These import statements import the following classes into our Applet class:

java.applet.Applet.
java.awt.Graphics.

Without these import statements, the Java compiler cannot recognize the Applet and Graphics classes.

Applet class

Every Applet is a subclass of the java.applet.Applet class. The basic Applet class provides methods for derived classes to call, in order to obtain information about the browser context and services.

These methods do the following:

  • Get the Applet parameters

  • Get the network location of the HTML file containing the Applet

  • Get the network location of the Applet class directory

  • Print the status information of the browser

  • Get an image

  • Get an audio clip

  • Play an audio clip

  • Adjust the size of this Applet

In addition, the Applet class provides an interface that viewers or browsers can use to obtain information about the Applet and control its execution.

The viewer may be:

  • Request information about the Applet author, version, and copyright

  • Description of the parameters recognized by the Applet

  • Initialize the Applet

  • Destroy the Applet

  • Start the execution of the Applet

  • End the execution of the Applet

The Applet class provides default implementations for these methods, which can be overridden as needed.

The "Hello, World" applet is written according to standards. The only method that is rewritten is the paint method.

Applet invocation

An Applet is a Java program. It generally runs inside a web browser that supports Java. Because it has complete Java API support, an Applet is a fully functional Java application.

The <applet> tag is the basis for embedding Applets in HTML files. Here is an example of calling the "Hello World" applet;

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>

Note: You can refer to the HTML Applet tag to learn more about calling applets from HTML.

<applet> tag attributes specify the Applet class to be executed. width and height are used to specify the initial size of the Applet running panel. The Applet must use </applet> tags to close.

If the Applet accepts parameters, the parameter values must be added in the <param> tag, which is located between the <applet> and </applet> between. Browsers ignore the text and other tags between the <applet> tags.

Browsers that do not support Java cannot execute <applet> and </applet> and is therefore visible between the tags and has no relationship with the applet. Anything displayed between the tags in browsers that do not support Java is visible.

The Viewer or browser looks for compiled Java code at the location of the document. To specify the path of the document, use the codebase attribute of the <applet> tag to specify the path.

As shown below:

<applet codebase="http://amrood.com/applets
code="HelloWorldApplet.class" width="320" height="120">

If the Applet is in a package other than the default package, then the package must be specified in the code attribute, for example:

<applet code="mypackage.subpackage.TestApplet.class"
           width="320" height="120">

Get applet parameters

The following example demonstrates how to use an Applet response to set the parameters specified in the file. The Applet displays a black chessboard pattern and the second color.

The second color and the size of each column are specified by the Applet parameters in the document.

CheckerApplet gets its parameters in the init() method. It can also get its parameters in the paint() method. However, it is convenient and efficient to get values and save settings when the Applet starts, rather than getting values every time it refreshes.

The Applet viewer or browser calls the init() method each time the Applet runs. After loading the Applet, the Viewer immediately calls the init() method (Applet.init() does nothing), overrides the default implementation, and adds some custom initialization code.

The Applet.getParameter() method retrieves the parameter value by providing the parameter name. If the obtained value is a number or other non-character data, it must be parsed as a string type.

The following is the modification of CheckerApplet.java:

import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
   int squareSize = 50;// Initialize the default size
   public void init() {}
   private void parseSquareSize(String param) {}
   private Color parseColor(String param) {}
   public void paint(Graphics g) {}
}

Below are the init() method of the CheckerApplet class and the private parseSquareSize() method:

public void init()
{
   String squareSizeParam = getParameter("squareSize");
   parseSquareSize(squareSizeParam);
   String colorParam = getParameter("color");
   Color fg = parseColor(colorParam);
   setBackground(Color.black);
   setForeground(fg);
}
private void parseSquareSize(String param)
{
   if (param == null) return;
   try {
      squareSize = Integer.parseInt(param);
   }
   catch (Exception e) {
     // Retain the default value
   }
}

The Applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a string into an integer, and throws an exception when the parameter is invalid.

Therefore, the parseSquareSize() method also catches exceptions and does not allow the Applet to accept invalid input.

The Applet calls the parseColor() method to parse the color parameter into a Color value. The parseColor() method performs a series of string comparisons to match the parameter value with predefined color names. You need to implement these methods to make the Applet work.

Specify applet parameters

The following example is an HTML file that embeds the CheckerApplet class. The HTML file specifies two parameters for the applet using the <param> tag.

<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>

Note: Parameter names are case-insensitive.

Conversion of application to Applet

Converting a graphical Java application (that is, an application using AWT and started with the java program launcher) to an applet embedded in a web page is very simple.

The following are several steps to convert an application to an Applet:

  • Write an HTML page that includes tags capable of loading the applet code.

  • Write a subclass of JApplet and set it as public. Otherwise, the Applet cannot be loaded.

  • Eliminate the main() method of the application. Do not construct a frame window for the application because your application is to be displayed in the browser.

  • Move the initialization code from the constructor of the frame window in the application to the init() method of Applet. You do not need to explicitly construct the Applet object; the browser will instantiate an object by calling the init() method.

  • Remove the call to the setSize() method, as the size for Applet is already set by the width and height parameters in the HTML file.

  • Remove the call to the setDefaultCloseOperation() method. The Applet cannot be closed; it terminates with the browser.

  • If the application calls the setTitle() method, eliminate the call to this method. The applet cannot have a title bar. (Of course, you can name the web page itself using the title tag in html)

  • Do not call setVisible(true), the Applet is automatically displayed.

Event Handling

The Applet class inherits many event handling methods from the Container class. The Container class defines several methods, such as processKeyEvent() and processMouseEvent(), which are used to handle special types of events, and there is also a method called processEvent to capture all events.

To respond to an event, the Applet must override the appropriate event handling method.

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
 
public class ExampleEventHandling extends Applet
                             implements MouseListener {
 
    StringBuffer strBuffer;
 
    public void init() {
         addMouseListener(this);
         strBuffer = new StringBuffer();
        addItem("initializing the applet ");
    }
 
    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);
 
         //在矩形内显示字符串。
        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("鼠标点击! ");
    }
}

以下是如何调用该 Applet:

<html>
<title>事件处理</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>

最初运行时,Applet 显示 "初始化 Applet。启动 Applet。",然后你点击矩形框,就会显示 "鼠标点击"。

显示图片

Applet 可以显示 GIF、JPEG、BMP 等其他格式的图片。为了在 Applet 中显示图片,你需要使用 java.awt.Graphics 类的 drawImage() 方法。

以下示例演示了显示图片的所有步骤:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
  private Image image;
  private AppletContext context;
  public void init()
  {
      context = this.getAppletContext();
      String imageURL = this.getParameter("image");
      if(imageURL == null)
      {
         imageURL = "java.jpg";
      }
      try
      {
         URL url = new URL(this.getDocumentBase(), imageURL);
         image = context.getImage(url);
      }catch(MalformedURLException e)
      {
         e.printStackTrace();
         // 显示在浏览器状态栏中
         context.showStatus("无法加载图片!");
      }
   }
   public void paint(Graphics g)}
   {
      context.showStatus("Displaying image");
       200, 84, null);
      g.drawString("www.javalicense.com", 35, 100);
   } 
}

The following is the call to the applet:

<html>
<title>The ImageDemo applet</title>/title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>

Play audio

An Applet can play audio by using the AudioClip interface in the java.applet package. The AudioClip interface defines three methods:

  • public void play(): Play the audio clip once from the beginning.

  • public void loop(): Loop playback of the audio clip

  • public void stop(): Stop playing the audio clip

To obtain an AudioClip object, you must call the getAudioClip() method of the Applet class. Regardless of whether the URL points to a real audio file, this method will return the result immediately.

The file will only be downloaded when it is time to play the audio file.

The following example demonstrates all the steps to play an audio file:

import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
   private AudioClip clip;
   private AppletContext context;
   public void init()
   {
      context = this.getAppletContext();
      String audioURL = this.getParameter("audio");
      if(audioURL == null)
      {
         audioURL = "default.au";
      }
      try
      {
         URL url = new URL(this.getDocumentBase(), audioURL);
         clip = context.getAudioClip(url);
      }catch(MalformedURLException e)
      {
         e.printStackTrace();
         context.showStatus("Could not load audio file!");
      }
   }
   public void start()
   {
      if(clip != null)
      {
         clip.loop();
      }
   }
   public void stop()
   {
      if(clip != null)
      {
         clip.stop();
      }
   }
}

Here is the call to applet:

<html>
<title>The ImageDemo applet</title>/title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav">
</applet>
<hr>

You can use the test.wav on your computer to test the above example.