Return to index

Java Basics 2

 

Topics covered include :

  • Applets
  • Inheritance (extending a class)
  • Packages

 

Like applications, applets are created from classes. However, applets do not have a main() method as an entry point but, instead, have an init() method (and several other methods) to control specific aspects of applet execution.

This guide converts the simple application from Java Basics 1 to an applet, and describes the structure and elements of an applet.

 

Application to Applet

An applet is a 'mini application' designed to run in web pages.

The following code is the applet equivalent to the simplest 'Hello World' application from Java Basics 1. The structure and elements of the applet code are discussed after the section on how to run the applet just below.

 import java.applet.Applet;
import java.awt.Graphics;  
import java.awt.Color; 

 

public class SimpleApplet extends Applet {  
      String text;  

 

      public void init() { 
            text = "Hello World !";
            setBackground(Color.cyan);  
      } 

 

      public void start() {  
            System.out.println("Starting...");  
      }  

 

      public void stop() {  
            System.out.println("Stopping...");  
      }  

 

      public void destroy() {
            System.out.println("Preparing to unload...");  
      }  

 

      public void paint(Graphics g) {  
            System.out.println("Paint");  
            g.setColor(Color.blue);  
            g.drawRect(0, 0, getSize().width -1, getSize().height -1);  
            g.setColor(Color.red);  
            g.drawString(text, 15, 25);  
      }  
}  

The SimpleApplet class is declared public so that the program that runs the applet (a browser, or the SDK's appletviewer (via TJI) can access it.

 

Running the Applet

To see the applet in action, you need an HTML file with an Applet tag, as follows:

<html>  
     <body>  
          <applet code=SimpleApplet.class WIDTH=200 HEIGHT=100>  
                An applet will appear in this space ...  
          </applet>  
     </body>  
</html>   

The easiest way to run the applet is with TJI's Applet Runner ('Applets' tab). Set the HTML file as the main 'html' file because this HTML file is the starting file - it will load the applet (and specify its size).

To run an applet written with the Java 2 APIs (i.e. Swing) in a browser, the browser must be enabled for the Java 2 Platform. If your browser is not enabled for the Java 2 Platform, one would normally have to use appletviewer to run the applet - or install the Java Plug-in. The Java Plug-in lets one run applets on web pages under the 1.2 version of the Java VM instead of the web browser's (limited) default Java VM. However, TJI's AppletRunner can run both types of applet happily. The point is - if you write an applet for non-programmers to use via the internet (that is, with a browser), they may need to install the Java PlugIn first if the applet uses any Swing classes.

Method init() is called (and 'run') when the applet is loaded. Then method start(). If running in a web browser, and the user moves to a different page, method stop() is called. If the user returns to the page containing the applet, method start() is called again. So method init() is only called once, but start() and stop() are called when the applet gains and loses focus. For example, if the applet plays a tune, the tune would be loaded during the init() method, started playing in method start() and stopped playing in method stop(). Hence, it stops playing if you change web page.

 

Applet Structure and Elements

The Java API Applet class provides what you need to design the appearance, and manage the behavior, of an applet. This class provides a graphical user interface (GUI) component called a Panel and a number of control and painting methods. To create an applet, you extend ('subclass') the Applet class and implement the appearance and behavior that you want.

The applet's appearance is created by drawing onto the Panel or by attaching other GUI components such as buttons, scrollbars or text areas to the Panel . The applet's behavior is defined by overriding the four methods : init(), start(), stop() and destroy() as required (at least the first three). The Applet class also provides some other useful methods - you can have a look at the API for class Applet in TJI's 'Guru'.

 

JApplet

Class javax.swing.JApplet is an extended version of class java.applet.Applet that adds support for the JFC/Swing component architecture.

The JApplet class is slightly incompatible with class Applet. JApplet contains a JRootPane as it's only child. The contentPane should be the parent of any children of a JApplet. This is different to what you would do for class Applet.

For example, to add a child to an a java.applet.Applet you'd write:

applet.add(child);

However using JApplet you need to add the child to the JApplet's contentPane instead:

applet.getContentPane().add(child);

The same is true for setting LayoutManagers, removing components, listing children, etc. All these methods should normally be sent to the contentPane() instead of the JApplet itself.

The contentPane() will always be non-null. Attempting to set it to null will cause the JApplet to throw an exception. The default contentPane() will have a BorderLayout manager set on it.

This use of a contentPane is common to all Swing GUI containers whereas class Applet works like the older AWT GUI containers.

 

Extending a Class

Most classes of any complexity extend other classes. Any class that does not specify that it extends another class actually extends class Object by default. To extend another class means to write a new class that can use the fields and methods defined in the class being extended.

The class being extended is the 'parent' class, and the class doing the extending is the 'child' class. Another way to say this is that the child class inherits the fields and methods of its parent, or chain of parents. Child classes either call or override inherited methods. This is called 'single inheritance' (one direct parent).

The SimpleApplet class extends class Applet, which extends class Panel, which extends class Container. The Container class extends class Object, which is the parent of all Java classes.

The Applet class provides the init(), start(), stop(), destroy() and paint() methods you saw in the example applet. The SimpleApplet class overrides these methods to do what the SimpleApplet class needs them to do. The Applet class provides no functionality for these methods (only 'empty', 'do-nothing' methods).

However, the Applet class does provide functionality for the setBackground() method, which is called from the init() method (actually this method is inherited from further up the inheritance tree - from class java.awt.Component). Thus the call to setBackground() is an example of calling a method inherited from a parent class - in contrast to overriding a method inherited from a parent class.

You might wonder why the Java language provides methods without implementations. This is to provide conventions for everyone to use for consistency across Java APIs. If everyone wrote their own method to start an applet, for example, but gave it a different name such as 'begin' or 'go', the applet code would not be inter-operable with other programs and browsers, or portable across multiple platforms. For example, both Netscape and Internet Explorer know to look for methods called init() and start().

 

Applet Behavior

An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be appletviewer or TJI's AppletRunner. The underlying software controls the applet by calling the methods that the applet inherits from the Applet class.

* The 'init()' Method : The init() method is called when the applet is first created and loaded by the underlying software. This method performs one-time operations that the applet needs for its operation, such as creating the user interface or setting the font. In the example, the init method initializes the text string and sets the background color.

* The 'start()' Method : The start() method is called when the applet is visited, such as when the end user goes to a web page with an applet on it. The example prints a string to the console to tell you that the applet is starting. In a more complex applet, the start method would do things required at the start of the applet, such as starting an animation or playing sounds.

After the start() method executes, the event thread calls the paint() method to draw the applet's Panel . A thread is a single sequential flow of control within the applet, and every applet can run in multiple threads. Applet drawing methods are always called from a dedicated drawing and event-handling thread.

* The 'stop()' and 'destroy()' Methods : The stop() method stops the applet when the applet is no longer on the screen, such as when the end user goes to another web page. The example prints a string to the console to tell you that the applet is stopping. In a more complex applet, this method should do things like stopping an animation or sounds.

The destroy() method is called when the browser exits. Your applet should implement this method to do final cleanup, such as stopping any live threads.

 

Applet Appearance

The Panel provided in the Applet class inherits a paint() method from its parent Container class. To draw something onto the Applet's Panel , you implement (override) the paint() method to do the drawing.

The Graphics object passed to the paint() method defines a graphics context for drawing on the Panel. The Graphics object has methods for graphical operations such as setting drawing colors, and drawing graphics, images and text.

The paint() method for the SimpleApplet draws the "I'm a simple applet" string in red inside a blue rectangle.

      public void paint(Graphics g) {  
           System.out.println("Paint");  
           // Set drawing color to blue  
           g.setColor(Color.blue);  
           // Specify the x, y, width and height for a rectangle  
           g.drawRect(0, 0, getSize().width -1, getSize().height -1);  
           // Set drawing color to red  
           g.setColor(Color.red);  
           // Draw the text string at the (15, 25) x-y location  
           g.drawString(text, 15, 25);  
     }  


Packages

The applet code also has three import statements at the top. Applications of any size, and all applets, use import statements to find and access ready-made Java API classes. These API classes are arranged into packages. This is true whether the Java API classes come in the Java platform download, from a third-party, or are classes you write yourself and store in a directory separate from the program.

At compile time, a program uses import statements to locate and reference compiled Java API classes stored in packages elsewhere on the local or networked system. A compiled class in one package can have the same name as a compiled class in another package. The package name differentiates the two classes.

The examples in Java Basics 1 did not need a package declaration to use the System Java API class because the System class is in the java.lang package that is included by default - so you don't need an import java.lang.* statement to use the classes in that package.

When a class or interface is part of a package, a package statement must be the first line of code (statement) in the class.

For example,

package java.lang;

will be specified at the start of the source code for class String.

When no package is declared, the class or interface becomes part of the default, no-name package.

 

Download and run ...

An improved version of the applet project is available for download as a TJI project on our web site - in the 'Resources' page.

Simply download the zip file and then choose 'Project Import' from the 'Project' menu. Select the zip file and the project will be imported and setup automatically. Now simply click on the 'Run' button to compile and run the applet.

Once running in TJI's AppletRunner, use the 'start' and 'stop' buttons to invoke the applet's start() and stop() methods. Then try changing the code and re-run the applet.

 

Note : Some parts of this document were based on 'Essentials of the Java Programming Language' - a book by Monica Pawlan, also on-line at Sun's java site.

Return to index