CS 136 - Lecture 36

  1. Applets
    1. Applet life cycle
    2. Writing Applets instead of applications
    3. An Example


Applets differ from applications by being executable from web pages.

Applet life cycle


public void init() - executed once when applet starts up

Usually includes all code for layout and initialization of object creation

public void start() - executed after init & every time return to page containing applet

public void stop() - called to stop applet (usually not necessary)

public void destroy() - called when applet being removed from memory
- used to release or destroy any resources in use.

Writing Applets instead of applications

  1. Include: import java.applet.*;

  2. Class should extend Applet rather than Frame;

  3. Replace constructor by public void init(){...} method.

    Omit method calls to super, setVisible, or setSize. Note that default layout manager for Applet is FlowLayout (rather than BorderLayout used by Frame) so may have to explicitly setLayout if desire layout different from FlowLayout.

  4. Omit main static method.

    If no interaction with environment then can consider start() as the main program and call other methods from there. If applet works via interaction with environment then often omit start() or just have it reinitialize state so can start over.

  5. Create web page with:
    <applet archive="JarName.jar" code="MainClass.class" width=140 height=200> </applet>

An Example

Consider the StopWatch applet that runs in the page describing Assignment 9.