Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA APPLET

An Applet skeleton

Applets are built using an application framework. You inherit from class Applet and override the appropriate methods. Most of the time you’ll be concerned with only a few important methods that have to do with how the applet is built and used on a Web page. These methods are:

Method

Operation

init( )

Called when the applet is first created to perform first-time initialization of the applet

start( )

Called every time the applet moves into sight on the Web browser to allow the applet to start up its normal operations (especially those that are shut off by stop( )). Also called after init( ).

paint( )

Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to perform special painting on the canvas of an applet.

stop( )

Called every time the applet moves out of sight on the Web browser to allow the applet to shut off expensive operations. Also called right before destroy( ).

destroy( )

Called when the applet is being unloaded from the page to perform final release of resources when the applet is no longer used

Consider the paint( ) method. This method is called automatically when the Component (in this case, the applet) decides that it needs to update itself – perhaps because it’s being moved back onto the screen or placed on the screen for the first time, or perhaps some other window had been temporarily placed over your Web browser. The applet calls its update( ) method (defined in the base class Component), which goes about restoring everything, and as a part of that restoration calls paint( ). You don’t have to override paint( ), but it turns out to be an easy way to make a simple applet, so we’ll start out with paint( ).

When update( ) calls paint( ) it hands it a handle to a Graphics object that represents the surface on which you can paint. This is important because you’re limited to the surface of that particular component and thus cannot paint outside that area, which is a good thing or else you’d be painting outside the lines. In the case of an applet, the surface is the area inside the applet.

The Graphics object also has a set of operations you can perform on it. These operations revolve around painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc. (Note that you can look all this up in your online Java documentation if you’re curious.) There are some methods that allow you to draw characters, however, and the most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applet’s drawing surface. This location is given in pixels, so it will look different on different machines, but at least it’s portable.

 


Previous

Next