APPENDIX

D   Applet Basics

As explained earlier in this book, JDK 9 deprecates the applet API. As a result, applets are not recommended for new code, with Java Web Start providing an excellent alternative. However, you may encounter legacy applets that require maintenance or that need to be converted into applications. Thus, for the benefit of those readers working with legacy applets, this appendix provides a brief introduction to the basics.

Applets are based on the Applet class. The Applet class is contained in the java.applet package. Beginning with JDK 9, this package is part of the java.desktop module. Applet contains several methods that give you detailed control over the execution of your applet. In addition, java.applet defines three interfaces, AppletContext, AudioClip, and AppletStub, which are often used by applets.

REMEMBER The Applet API has been deprecated by JDK 9, and applets are not recommended for new code.

Two Types of Applets

It is important to state at the outset that there are two varieties of applets based on Applet. The first are those that extend the Applet class directly. These applets use the Abstract Window Toolkit (AWT) to provide the graphical user interface (or use no GUI at all). This style of applet has been available since Java was first created.

The second type of applets are those that extend the Swing class JApplet, which extends Applet. Swing applets use the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface than does the AWT. Thus, Swing-based applets are commonplace.

This appendix begins with AWT-based applets. However, because JApplet inherits Applet, all the features of Applet are also available in JApplet, and much of the information applies to both types. Therefore, even if you are interested in only Swing applets, the information on AWT-based applets is still relevant and necessary. Understand, however, that when creating Swing-based applets, some additional constraints apply, and these are described later in this appendix.

Applet Basics

AWT-based applets are direct subclasses of Applet. Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer. The illustrations shown in this appendix were created with the standard applet viewer, called appletviewer, provided by the JDK. Be aware, however, that beginning with JDK 9, appletviewer is a deprecated tool.

Unlike a Java console application, execution of an applet does not begin at main( ). Actually, few applets even have main( ) methods. Instead, execution of an applet is started and controlled with an entirely different mechanism, which will be explained shortly. Output to an applet’s window is not performed by System.out.println( ). Rather, in an AWT-based applet, output is handled with various AWT methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is also handled differently than in a console application, typically through an AWT-based control, such as a push button or an edit box.

There are two basic ways in which an applet can be included in a web page. The first is through the Java Network Launch Protocol (JNLP). This method offers the most flexibility, especially as it relates to rich Internet applications. Thus, JNLP was often the choice for real-world applets. (A detailed discussion of JNLP is beyond the scope of this book, but a brief introduction to JNLP is found in Appendix C.) The second basic approach to deploying an applet is to specify the applet directly in an HTML file, without the use of JNLP. Originally, this was by use of the APPLET tag, and this is the way applets were launched when Java was first created. When an APPLET tag is encountered in the HTML file, the specified applet will be executed by a Java-enabled web browser. Although the APPLET tag is traditional, the OBJECT tag offers a standardized alternative, and you will likely encounter it, especially in newer HTML files.

When developing applets, you can use either the APPLET or OBJECT tag to easily view and test the applet. To do so, simply include a comment at the head of your Java source code file that contains the APPLET or OBJECT tag. This way, your code is documented with the necessary HTML statements needed by your applet, and you can test the compiled applet by starting appletviewer with your Java source code file specified as the target. Here is an example of such a comment that uses the APPLET tag:

Images

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Because the inclusion of such a tag makes testing applets easier, the applets shown here will contain the appropriate, traditional APPLET tag embedded in a comment. You are free to substitute OBJECT if you desire.

NOTE For modern versions of Java, there are significant security issues surrounding applets. For example, beginning with the release of Java 7, update 21, Java applets must be signed to prevent security warnings when run in a browser. In fact, in some cases, the applet may be prevented from running. Consult Oracle’s documentation for the latest security information pertaining to applets. Fortunately, if you simply want to try the examples shown in this appendix, you can easily do so by using appletviewer.

The Applet Class

The Applet class encapsulates an applet. It defines a number of methods. The most fundamental are those methods that control an applet’s execution, such as starting and stopping. These are the life cycle methods init( ), start( ), stop( ), and destroy( ). Other methods load and display images, load and play audio clips, access parameters, and so on. Remember, all of these methods, and the entire applet API, are deprecated as of JDK 9. Thus, compiling an applet with JDK 9 or later will generate deprecation warnings.

Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for the AWT-based graphical interface. Thus, Applet provides all of the necessary support for window-based activities and handling events. (An overview of the AWT is presented in Chapters 25 and 26.)

Applet Architecture

As a general rule, an applet is a GUI-based program. As such, its architecture is different from console-based programs. First, applets are event driven. Here is how the process works. An applet waits until an event occurs. The run-time system notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return. This is a crucial point. For the most part, your applet should not enter a “mode” of operation in which it maintains control for an extended period. Instead, it must perform specific actions in response to events and then return control to the run-time system. In those situations in which your applet needs to perform a repetitive task on its own (for example, displaying a scrolling message across its window), you must start an additional thread of execution.

Second, the user initiates interaction with an applet—not the other way around. As you know, in a console-based program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks the mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. Applets can contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated. For AWT-based applets, the basic AWT GUI is used. For Swing applets, the Swing GUI is used.

An Applet Skeleton

All but the most trivial applets override a set of methods that provide the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets. These are the applet’s life cycle methods, and they are defined by Applet. Default implementations for these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them. AWT-based applets will often override the paint( ) method, which is defined by the AWT Component class. This method is called when the output displayed in the applet’s window must be redisplayed. (As explained later, Swing-based applets use a different mechanism and will not usually override paint( ).)

The four life cycle methods plus paint( ) can be assembled into the skeleton shown here:

Images

Although this skeleton is quite short, it can be compiled and run. When run, it generates the following window when viewed with appletviewer. Of course, in this and the subsequent example, the precise look of the appletviewer frame may differ based on your execution environment.

Images

Applet Initialization and Termination

It is important to understand the order in which the various methods shown in the preceding skeleton are called. When an applet begins, the following methods are called, in this sequence:

1.  init( )

2.  start( )

3.  paint( )

When an applet is terminated, the following sequence of method calls takes place:

1.  stop( )

2.  destroy( )

Let’s look more closely at these methods.

init( )

The init( ) method is the first method to be called. This is where applet initialization is performed. This method is called only once during the execution of the applet.

start( )

The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint( )

The paint( ) method is called each time an AWT-based applet’s output must be redrawn. As explained, paint( ) is not specified by Applet, but is inherited from Component. Thus, it works in an AWT-based applet the same as it does in an AWT-based GUI application as described in Chapter 25. Furthermore, to request repainting, call repaint( ), as also described in Chapter 25. Remember, the paint( ) method is needed only in AWT-based applets that draw output to their window. In the preceding example, paint( ) is used to display a string in the applet’s window. If the applet uses only controls, for example, then paint( ) is not needed.

stop( )

The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. An important use of stop( ) is to suspend threads that don’t need to run when the applet is not visible. If the user returns to the page, the threads can be restarted when start( ) is called.

destroy( )

The destroy( ) method is called when the environment determines that the applet needs to be removed completely from memory. At this point, any resources used by the applet should be released. The stop( ) method is always called before destroy( ).

Swing Applets

The second type of applet you may encounter is Swing-based. Swing-based applets are similar to AWT-based applets, but with an important difference: a Swing applet extends JApplet rather than Applet. Because JApplet is derived from Applet it includes all of the functionality found in Applet and adds support for Swing. JApplet is a top-level Swing container, which means that it is not derived from JComponent. Because JApplet is a top-level container, it includes the various panes described in Chapter 31. This means that all components are added to JApplet’s content pane in the same way that components are added to JFrame’s content pane.

Swing applets use the same four life cycle methods as just described: init( ), start( ), stop( ), and destroy( ). Of course, you need override only those methods that are required by your applet. Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the paint( ) method. If you need to paint directly to the applet window, then you will typically override its paintComponent( ) method, as described in Chapter 31.

One other point: All interaction with components in a Swing applet must take place on the event-dispatching thread, as is the case with all Swing applications.

Here is an example of a Swing applet. It uses two buttons and a text field. Each time a button is pressed, the action is displayed in the text field. Notice that only init( ) is overridden. There is no need to override the other life cycle methods because their default versions are adequate.

Images

Images

Images

Here is MySwingApplet as displayed by appletviewer:

Images

There are two important things to notice about this applet. First, MySwingApplet extends JApplet. As explained, all Swing-based applets extend JApplet rather than Applet. Second, the init( ) method initializes the Swing components on the event-dispatching thread by setting up a call to makeGUI( ). Notice that this is accomplished through the use of invokeAndWait( ) rather than invokeLater( ). Applets must use invokeAndWait( ) because the init( ) method must not return until the entire initialization process has been completed. In essence, the start( ) method cannot be called until after initialization, which means that the GUI must be fully constructed.

Inside makeGUI( ), the two buttons and label are created, and the action listeners are added to the buttons. Finally, the components are added to the content pane. Although this example is quite simple, this same general approach must be used when building any Swing GUI that will be used by an applet.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74