Documentation

The Java™ Tutorials
Hide TOC
Defining an Applet Subclass定义Applet子类
Trail: Deployment
Lesson: Java Applets
Section: Getting Started With Applets小程序入门

Defining an Applet Subclass定义Applet子类

Every Java applet must define a subclass of the Applet or JApplet class. 每个Java小程序必须定义Applet子类或JApplet类的子类。In the Hello World applet, this subclass is called HelloWorld. 在Hello World小程序中,此子类称为HelloWorldThe following is the source for the HelloWorld class.以下是HelloWorld类的源代码。

import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;

public class HelloWorld extends JApplet {
    //Called when this applet is loaded into the browser.
    public void init() {
        //Execute a job on the event-dispatching thread; creating this applet's GUI.
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    JLabel lbl = new JLabel("Hello World");
                    add(lbl);
                }
            });
        } catch (Exception e) {
            System.err.println("createGUI didn't complete successfully");
        }
    }
}

Java applets inherit significant functionality from the Applet or JApplet class, including the capabilities to communicate with the browser and present a graphical user interface (GUI) to the user.Java小程序继承了AppletJApplet类的重要功能,包括与浏览器通信和向用户显示图形用户界面(GUI)的功能。

An applet that will be using GUI components from Swing (Java's GUI toolkit) should extend the javax.swing.JApplet base class, which provides the best integration with Swing's GUI facilities.将使用Swing(Java的GUI工具包)GUI组件的小程序应该扩展javax.swing.JApplet基类,该基类提供了与Swing GUI工具的最佳集成。

JApplet provides a root pane, which is the same top-level component structure as Swing's JFrame and JDialog components, whereas Applet provides just a basic panel. JApplet提供了一个根窗格,它与Swing的JFrameJDialog组件具有相同的顶级组件结构,而Applet只提供了一个基本面板。See How to Use Root Panes for more details on how to use this feature.有关如何使用此功能的详细信息,请参阅如何使用根窗格

An applet can extend the java.applet.Applet class when it does not use Swing's GUI components.当小程序不使用Swing的GUI组件时,它可以扩展java.applet.Applet类。


Previous page: Getting Started With Applets
Next page: Methods for Milestones