Java 简明教程

Java - Applet Basics

一个 applet 是一个在 Web 浏览器中运行的 Java 程序。小应用程序可以是一个功能齐全的 Java 应用程序,因为它可以使用整个 Java API。

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.

小应用程序与独立 Java 应用程序之间有一些重要的区别,包括以下区别 −

There are some important differences between an applet and a standalone Java application, including the following −

  1. An applet is a Java class that extends the java.applet.Applet class.

  2. A main() method is not invoked on an applet, and an applet class will not define main().

  3. Applets are designed to be embedded within an HTML page.

  4. When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user’s machine.

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

  6. The JVM on the user’s machine creates an instance of the applet class and invokes various methods during the applet’s lifetime.

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

  8. Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet in Java

Applet 类中的四种方法为你提供了构建任何重要小程序的基础架构 −

Four methods in the Applet class gives you the framework on which you build any serious applet −

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

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

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

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

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

Flow of Java Applet Life Cycle

小程序生命周期方法会自动调用。下图显示了小程序生命周期的流程。

Applet life cycle methods are called automatically. The following diagram shows the flow of an applet life cycle.

java applet life cycle

A Simple Java Applet "Hello, World"

这是一个名为 HelloWorldApplet.java 的简单小程序 −

Following is a simple applet named 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 bring the classes into the scope of our applet class −

  1. java.applet.Applet

  2. java.awt.Graphics

如果没有这些 import 语句,则 Java compiler 将无法识别小应用程序类所引用的 Applet 和 Graphics 类。

Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to.

The Applet Class

每个小程序都是 java.applet.Applet 类的扩展。基本 Applet 类提供了派生小程序类可以调用的方法,以从浏览器环境获取信息和服务。

Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context.

其中包括执行以下操作的方法 −

These include methods that do the following −

  1. Get applet parameters

  2. Get the network location of the HTML file that contains the applet

  3. Get the network location of the applet class directory

  4. Print a status message in the browser

  5. Fetch an image

  6. Fetch an audio clip

  7. Play an audio clip

  8. Resize the applet

此外,Applet 类还提供了一个接口,供查看器或浏览器获取有关小程序的信息并控制小程序的执行。查看器可以 −

Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet’s execution. The viewer may −

  1. Request information about the author, version, and copyright of the applet

  2. Request a description of the parameters the applet recognizes

  3. Initialize the applet

  4. Destroy the applet

  5. Start the applet’s execution

  6. Stop the applet’s execution

Applet 类为每种方法提供默认实现。可以根据需要覆盖这些实现。

The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary.

“Hello, World”小程序在当前状态下是完整的。唯一被覆盖的方法是 paint 方法。

The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet

可以通过将指令嵌入 HTML 文件并在小程序查看器或支持 Java 的浏览器中查看该文件来调用小程序。

An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

<applet> tag 是将一个小应用程序嵌入 HTML 文件中的基础。以下是一个调用“Hello, World”小应用程序的示例−

The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes 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 −你可以参阅 HTML Applet Tag 以详细了解如何从 HTML 中调用小应用程序。

Note − You can refer to HTML Applet Tag to understand more about calling applet from HTML.

<applet> 标签的 code 属性是必需的。它指定要运行的 Applet 类。还要求宽度和高度来指定小程序运行的面板的初始大小。小程序指令必须使用 </applet> 标签关闭。

The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and height are also required to specify the initial size of the panel in which an applet runs. The applet directive must be closed with an </applet> tag.

如果小程序带有参数,可以通过在 <applet> 和 </applet> 之间添加 <param> 标签来传递参数值。该浏览器将忽略 applet 标签之间的文本和其他标签。

If an applet takes parameters, values may be passed for the parameters by adding <param> tags between <applet> and </applet>. The browser ignores text and other tags between the applet tags.

不支持 Java 的浏览器不会处理 <applet> 和 </applet>。因此,标签之间的任何内容都与该小程序无关,并且在不支持 Java 的浏览器中是可见的。

Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.

该查看器或浏览器在文档位置查找已编译的 Java 代码。若要另行指定,请使用 <applet> 标签的 codebase 属性,如以下代码所示:

The viewer or browser looks for the compiled Java code at the location of the document. To specify otherwise, use the codebase attribute of the <applet> tag as shown −

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

如果小程序位于其他包中,而且不是默认包,则必须使用句点 (.) 来分隔包/类组件,并通过 code 属性来指定包含的包。例如:

If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period character (.) to separate package/class components. For example −

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

Getting Applet Parameters

以下示例演示如何让小程序响应文档中指定的设置参数。该小程序显示黑白相间的棋盘格图案。

The following example demonstrates how to make an applet respond to setup parameters specified in the document. This applet displays a checkerboard pattern of black and a second color.

可以在文档中将第二种颜色和每个正方形的大小指定为小程序的参数。

The second color and the size of each square may be specified as parameters to the applet within the document.

CheckerApplet 在 init() 方法中获取其参数。它还可以在 paint() 方法中获取其参数。但是,在 applet 开始时获取值并保存设置(而不是每次刷新时),是方便且有效的。

CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint() method. However, getting the values and saving the settings once at the start of the applet, instead of at every refresh, is convenient and efficient.

小程序查看器或浏览器调用它运行的每个小程序的 init() 方法。该查看器在加载小程序后立即调用 init() 一次。(Applet.init() 被实现为不做任何事情。)为了插入定制初始化代码,请覆盖默认实现。

The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init() once, immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override the default implementation to insert custom initialization code.

Applet.getParameter() 方法获取给定参数名称的参数(参数值始终为字符串)。如果该值为数字或其他非字符数据,则必须对字符串进行解析。

The Applet.getParameter() method fetches a parameter given the parameter’s name (the value of a parameter is always a string). If the value is numeric or other non-character data, the string must be parsed.

以下是 CheckerApplet.java 的结构:

The following is a skeleton of CheckerApplet.java −

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

public class CheckerApplet extends Applet {
   int squareSize = 50;   // initialized to default size
   public void init() {}
   private void parseSquareSize (String param) {}
   private Color parseColor (String param) {}
   public void paint (Graphics g) {}
}

以下是 CheckerApplet 的 init() 和私有 parseSquareSize() 方法:

Here are CheckerApplet’s init() and private parseSquareSize() methods −

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) {
      // Let default value remain
   }
}

该小程序调用 parseSquareSize() 来解析 squareSize 参数。parseSquareSize() 调用库方法 Integer.parseInt(),它解析字符串并返回一个整数。每当其参数无效时,Integer.parseInt() 都会引发异常。

The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt() throws an exception whenever its argument is invalid.

因此,parseSquareSize() 捕获异常,而不是让小程序由于错误输入而失败。

Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad input.

该小程序调用 parseColor() 将 color 参数解析为 Color 值。parseColor() 执行一系列字符串比较,以将参数值与预定义颜色的名称匹配。您需要实现这些方法才能使此小程序工作。

The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a series of string comparisons to match the parameter value to the name of a predefined color. You need to implement these methods to make this applet work.

Specifying Applet Parameters

以下是其中嵌入 CheckerApplet 的 HTML 文件的示例。该 HTML 文件通过 <param> 标签指定小程序的两个参数。

The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file specifies both parameters to the applet by means of the <param> tag.

Example

<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 - 参数名称不区分大小写。

Note − Parameter names are not case sensitive.

Application Conversion to Applets

将图形 Java 应用程序(即使用 AWT、并且可以使用 Java 程序启动器启动的应用程序)很容易转换为可嵌入到网页中的小程序。

It is easy to convert a graphical Java application (that is, an application that uses the AWT and that you can start with the Java program launcher) into an applet that you can embed in a web page.

以下是将应用程序转换为小程序的具体步骤。

Following are the specific steps for converting an application to an applet.

  1. Make an HTML page with the appropriate tag to load the applet code.

  2. Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be loaded.

  3. Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be displayed inside the browser.

  4. Move any initialization code from the frame window constructor to the init method of the applet. You don’t need to explicitly construct the applet object. The browser instantiates it for you and calls the init method.

  5. Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.

  6. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.

  7. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You can, of course, title the web page itself, using the HTML title tag.)

  8. Don’t call setVisible(true). The applet is displayed automatically.

Event Handling

小应用程序从 Container 类继承一组事件处理方法。Container 类定义了一些方法(如处理特定类型事件的 processKeyEvent 和 processMouseEvent)以及一个通用方法 processEvent。

Applets inherit a group of event-handling methods from the Container class. The Container class defines several methods, such as processKeyEvent and processMouseEvent, for handling particular types of events, and then one catch-all method called processEvent.

为了对事件做出反应,需要覆盖适当的事件特定方法。

In order to react to an event, an applet must override the appropriate event-specific method.

Example

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 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! ");
   }
}

现在,我们按如下方式调用此小应用程序 −

Now, let us call this applet as follows −

<html>
   <title>Event Handling</title>
   <hr>
   <applet code = "ExampleEventHandling.class"
      width = "300" height = "300">
   </applet>
   <hr>
</html>

最初,小应用程序将显示“初始化小应用程序。正在启动小应用程序。”然后,一旦您点击矩形内的某个位置,“鼠标已点击”也将显示出来。

Initially, the applet will display "initializing the applet. Starting the applet." Then once you click inside the rectangle, "mouse clicked" will be displayed as well.

Displaying Images

小应用程序可以显示 GIF、JPEG、BMP 等格式的图像。若要在小应用程序内显示图像,请使用 java.awt.Graphics 类提供的 drawImage() 方法。

An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you use the drawImage() method found in the java.awt.Graphics class.

以下是说明显示图像的所有步骤的一个示例 −

Following is an example illustrating all the steps to show images −

Example

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();
         // Display in browser status bar
         context.showStatus("Could not load image!");
      }
   }

   public void paint(Graphics g) {
      context.showStatus("Displaying image");
      g.drawImage(image, 0, 0, 200, 84, null);
      g.drawString("www.javalicense.com", 35, 100);
   }
}

现在,我们按如下方式调用此小应用程序 −

Now, let us call this applet as follows −

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

Playing Audio

小应用程序可以播放由 java.applet 包中的 AudioClip 接口表示的音频文件。AudioClip 接口有三个方法,包括 −

An applet can play an audio file represented by the AudioClip interface in the java.applet package. The AudioClip interface has three methods, including −

  1. public void play() − Plays the audio clip one time, from the beginning.

  2. public void loop() − Causes the audio clip to replay continually.

  3. public void stop() − Stops playing the audio clip.

要获取 AudioClip 对象,您必须调用 Applet 类的 getAudioClip() 方法。getAudioClip() 方法会立即返回,而不管 URL 是否解析为实际的音频文件。只有在尝试播放音频片段时才会下载音频文件。

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file. The audio file is not downloaded until an attempt is made to play the audio clip.

以下是说明播放音频的所有步骤的一个示例 −

Following is an example illustrating all the steps to play an audio −

Example

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();
      }
   }
}

现在,我们按如下方式调用此小应用程序 −

Now, let us call this applet as follows −

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

可在您的 PC 上使用 test.wav 测试上述示例。

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