Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/

Introduction to Applets

Java Programming, Lecture Notes # 18, Revised 10/03/99.

Preface
Introduction
A Brief Word about Overriding Methods
A Brief Word about the Java Class Hierarchy
The "Hello World" Applet
A Brief Word about Packages
A Brief Word about Inheritance and Applets
A Brief Word about the HTML Page
Running Applets in Standalone Mode
Sample Program
Review Questions for Lesson 18

Preface

Students in Prof. Baldwin's Introductory Java Programming classes at ACC are responsible for knowing and understanding all of the material in this lesson (except that they are not responsible for detailed information that is specific to C++).

The detailed material on C++ is provided as supplementary material for the benefit of those persons who are already familiar with C++ and who are making the transition into Java.

Introduction

Applets

This lesson provides a very brief introduction to the programming of Java Applets.

Two Approaches

To repeat some of what we said in an earlier lesson, Java programs can be written and executed in two ways:

A Third Approach

Actually we said that with a little extra programming effort, it is also possible to run most applets as standalone programs. We will illustrate this at the end of this lesson.

What About A Graphical User Interface (GUI)?

Programming a simple applet in Java is significantly different from programming a simple application. This is particularly true when the application doesn't make use of a Graphical User Interface (GUI). When the application does make use of a GUI, the programming requirements for the two are more similar.

When a simple graphical user interface is needed, applet programming can be easier than application programming. We will also illustrate this at the end of the lesson.

Applet Execution Mode

Applets are designed to be downloaded and executed on-line, under control of a Java-capable browser.

A Java-Capable Browser

What do we mean by a Java-Capable browser? We mean a browser that contains its own Java Virtual Machine, which (hopefully) is compatible with all the programming features included in your applet. As of August 1999, this compatibility issue continues to be a serious one, but not as serious as it was in past years.

The Java Virtual Machine

What do we mean by a Java Virtual Machine or JVM? A JVM is a program that is capable of extracting the bytecode data from the compiled class files and using them to cause the behavior of the computer to match what the Java programmer (hopefully) had in mind when she wrote the Java application or applet in the first place.

Using a Different Language to Produce Bytecode

Could you use another language (possibly one of your own design) to create applets? The answer is probably yes. All that would be necessary would be for your other language to create class files whose contents match the requirements of the JVM, although that may be much easier said than done. All the browser actually sees is the class files. It really doesn't know how they were created as long as they meet the specifications for the Java language and JVM.

Special Security Procedures Apply

Because applets are designed to be downloaded and executed on-line, special security procedures are implemented. Applet functionality is restricted by the browser in an attempt to prevent downloaded applets from damaging your computer or your data.

Note that such restrictions are not a function of the Java language. Rather, they are imposed by a security manager that is a part of browser. In theory, you could write your own browser that would impose no such requirements on the execution of applets (but that might not be a wise thing to do).

Security in JDK 1.1

Capabilities were designed into JDK 1.1 to allow the individual to decide the level of security restrictions that are to be imposed on applets when they are executed. However, as of August 1999, I don't believe that either the Netscape or Microsoft browser products are fully supporting this capability.

New Security Requirements in JDK 1.2

Actually, security is a moving target. Major changes in the security area were introduced in JDK 1.2 in December 1998. However, the details are far too complex for an introductory course in Java.

The topic of security will be discussed in more detail in a subsequent lesson on Advanced Java Programming.

Is a main() Method Required?

A stand-alone Java program (Java application) requires a method named main in its controlling class.

An Applet does not require a main method, but we will show at the end of this lesson that it is technically all right to include a main() method in an applet to support standalone operation.

A Brief Word about Overriding Methods

In order to understand the program code for an applet, it is necessary to have some understanding of the concept of overriding methods. This topic will be covered in more detail later, so this is simply an introduction to help you understand the applet code that is presented later in this lesson.

Runtime Polymorphism

Overriding methods is an aspect of inheritance and results in a mode of behavior that we refer to as runtime polymorphism. (You should already know about inheritance and runtime polymorphism as a result of studying one of the early lessons in this series on Object-Oriented Programming.)

Inheritance

New classes can be defined by extending (inheriting from) existing classes. The new class is often referred to as the subclass and the class being extended is often referred to as the superclass. (Many other names are used as well as explained in the earlier lesson on Object-Oriented Programming.)

When a new class extends an existing class, all the variables and methods which are members of the superclass (and which are members of all the ancestors of the superclass) become members of the subclass

This is an extremely important statement. Turn it over in your mind a few times to make sure that you realize the full impact of what I just said.

Modifying Behavior

In the event that the behavior specified by a method of the superclass (or one of its ancestors) is not appropriate for objects of the new type defined by the subclass, it is possible to rewrite the method in the subclass to cause it to impart different behavior for objects of the subclass type.

This is another extremely important statement. Make certain that you think about it and understand what it means. It might also be worthwhile for you to go back and review the section on overriding methods in the earlier lesson on Object-Oriented programming. That section contains a small, but very important sample program illustrating the general behavior of overridden methods.

Overriding a Method in Java

Rewriting the method in the subclass is referred to as overriding the method.

All that is required to override a method in Java is to use the same method signature in the subclass and then provide a different body for the method.

Overriding a Method in C++

C++ programmers may recall that the procedure for overriding a method in C++ is a little more complicated, requiring among other things that the method being overridden be originally defined as a virtual method.

A Brief Word about the Java Class Hierarchy

The Object Class

All classes automatically derive from a superclass named Object or from a direct or indirect subclass of Object.

All classes in Java form a hierarchical pyramid with the Object class at the top of the pyramid.

The Object class defines a number of methods that are inherited by and are available to all direct or indirect subclasses of the Object class. Similarly, in the standard Java class libraries, various direct and indirect subclasses of Object provide additional methods that are inherited by new subclasses that you define.

All Classes are Direct or Indirect Subclasses of Object

Whenever you define a new class, it is a subclass of Object by default. However, you will often want to take advantage of the functionality of existing subclasses of Object by extending one of those existing subclasses. That is the case when we define the class for and write the code for an applet.

When Should You Override Methods?

Sometimes, you will be content with leaving the inherited methods alone and either using them as defined, or ignoring them altogether. At other times, you will need to modify the behavior of certain inherited methods by overriding them in new classes that you define.

The "Hello World" Applet

What Is an Applet?

According to The Java Tutorial, by Mary Campione and Kathy Walrath, which at the time of this writing could be downloaded from http://java.sun.com:80/books/Series/Tutorial/index.html,
 

"... a Java Applet is a program that adheres to a set of conventions that allows it to run within a Java-compatible browser." 

Three Ways to Execute an Applet

There are at least two ways to execute a Java applet (actually three ways with a little extra programming effort).

AppletViewer

One way, and this is often the preferable way for testing, is to execute the applet using the AppletViewer program which is a standard part of the JDK.

Java-Capable Browser

A second way to execute a Java applet, and this is the way that you make applets available to others on your Web site, is to view it using a Java-capable browser program.

In both cases, it is necessary to produce an HTML file containing tags that reference the applet. HTML files will be discussed briefly a little later.

Running Applet in Standalone Mode

The third way to execute an applet is to run it in a standalone mode. This does not require an HTML file. It does require that a main() method is contained in the controlling class for the applet.

The "Hello World" Applet

A sample applet that displays Hello World follows.

Note that the controlling class for this applet

The various parts of the applet are presented and discussed later in this lesson.
 

/*Applet program hello3.java
This is a Java applet that produces the same
output as the application named hello1.java,
except this program runs under a browser or 
the Applet Viewer.
*********************************************************/

import java.applet.Applet;//see discussion on packages
import java.awt.Graphics;

public class hello3 extends Applet {
  //override the paint method
  public void paint(Graphics screen) {
    screen.drawString("Hello World",50,25);
  }
} //End hello3 class. 
//End applet

A Brief Word about Packages

What is a Package?

Packages are used in Java to group classes similar to the way libraries are used to group functions and classes in C++.

Packages will be discussed in more detail in a subsequent lesson. Suffice it for now to say that a package is nothing more and nothing less than the specification of a directory on your hard drive that contains a group of (probably) related class files.

Importing Classes

The above program contains two import statements.

Except for certain classes that are automatically imported (such as the System class) when a Java program is compiled, Java programs can import classes or packages containing classes in order to access the classes with minimal code.

Doing it the Hard Way

If we were to delete the import directives in the above program, we could still compile and run the program, but only if we made the modifications shown in boldface below.

As you can see, this requires more typing effort on your part.

public class hello3 extends java.applet.Applet {
  public void paint(java.awt.Graphics screen) { 
    screen.drawString("Hello World",50,25);
  }
} //End hello3 class. 

Why Use Import Directives?

The import directives are a convenience to the programmer making it possible to refer to the classes without the requirement to provide a fully qualified path name for every class.

Importing Packages

As an alternative to importing individual classes, you can import entire packages using a wildcard character as shown below. This may slow down compilation but will have no detrimental impact at runtime.

import java.applet.*;

import java.awt.*;

The Default Package

All classes are in packages, either the package specified when the class is defined, or in the default package.

All of the classes within a package can refer to each other without using fully qualified path names.

As mentioned above, packages will be discussed in more detail in a subsequent lesson.

A Brief Word about Inheritance and Applets

In both Java and C++, classes can inherit from other classes. (Inheritance will be discussed in more detail in a subsequent lesson.)

In Java, a class which inherits from another class is called a subclass and the inheritance is accomplished using the keyword extends. (Inheritance syntax is much different in C++.)

Applets Must Extend the Applet Class

Every applet must inherit a subclass from the Applet class by extending the Applet class (which was imported in the above program).

Furthermore, that subclass must be defined as public.

What About main()?

Applets do not need a main method (but may have one if you want to be able to run them in a standalone mode).

What Methods Must an Applet Override?

An applet must override at least one of the following methods, and can override more than one.

Overridden paint() Method

The overridden paint() method appears as shown in the following code fragment:

  public void paint(Graphics screen) { 
    screen.drawString("Hello World",50,25);
  }

Without going into detail at this point, the paint() method receives a reference to an object of type Graphics.

This reference is known locally by the name screen.

The Graphics class provides a method named drawString() that is used to "draw" a text string onto the Graphics object at a specified location.

In this case, the Graphics object represents the computer's screen. That isn't always the case, but the exceptions are too advanced for an introductory course in Java.

In this case, the string Hello World is drawn onto the Graphics object (and hence the screen) at a location of 50 pixels to the right and 25 pixels down from the top left-hand corner of the screen space occupied by the applet.

Where Are These Methods Defined?

init and start are methods of the Applet class.

paint is a method of the component class that is inherited by several intermediate classes and is finally inherited by the Applet class.

Why Override the Methods?

There are some complex issues surrounding the overriding and use of these methods that will be discussed in subsequent lessons. Since this lesson is simply a brief introduction to applets, these issues will not be discussed further here.

A Brief Word about the HTML Page

Where Does HTML come Into the Picture?

Applets are intended to be included in HTML pages and downloaded from a Web site to a client computer.

What is an <APPLET> Tag?

You use the HTML <APPLET> tag to specify the location of the applet subclass (controlling class) and the dimensions of the onscreen display area.

When the <APPLET> tag is encountered by a Java-capable browser, (or the AppletViewer program) it

It then invokes one of the three methods listed above for the object causing the Applet to execute.

These are Not Class Methods

Unlike main(), the methods named init(), start() and paint() are not class methods.

Therefore they cannot be invoked simply by joining the name of the method with the name of a class.

These are instance methods and an object is required to invoke them.

Creating HTML Files

Instructions for creating simple HTML files can be obtained from a variety of sources, including several online locations on the Web. You can find links to hundreds of HTML resources at http://html.about.com/.

(In fact, you can find hundreds of links to hundreds of different topics at http://about.com/.)

A Sample HTML File

There is no intention of providing a detailed discussion of HTML in this course of study. However, a minimum knowledge of HTML is required to work with applets. A sample HTML document that can be used to execute this Applet with the Applet Viewer or a Java-capable browser is shown below.

Appearance and Behavior of Applet

As a word of caution, in some cases, the appearance and behavior of your applet will not be exactly the same when viewed with the AppletViewer and when viewed with a Java-capable browsers. Always test your applets using one or more browsers before publishing them on your Web page (the appearance and behavior may differ between different browsers as well).
 

<HTML>
<HEAD>
<title>Hello World Applet</title>
</HEAD>
<BODY>
<applet code="hello3.class" width=300 height=100>
</applet>
</BODY>
</HTML>

Running Applets in Standalone Mode

Earlier in this lesson I made the following statement:

In some ways, when a graphical user interface is needed, applet programming is easier than application programming.

I am now going to show you what I meant by that statement.

The programs for most applets can be written so that can be run

Providing a Place for the Applet to Run

For simple applets, all that is required to run an applet in a standalone mode is to provide a place for the applet to run (recall that the browser normally provides the place for it to run). Some additional code is required to provide that place when running the applet in a standalone mode.

A main() Method in an Applet

Although an applet doesn't require a main() method, there is no harm in providing one. If you provide an appropriate main() method, it can be invoked by the JVM to run the applet in a standalone mode. Unfortunately, the complexity of the main() method goes beyond what we have covered so far and it will be awhile before we cover enough material that you will be able to understand most of what you see in the following main() method. In fact, most of this material is not covered until the Intermediate Java Programming course.

Sample Program

The following program will run

The comments pretty well explain what is going on. However, since we haven't covered any of the material involving the graphical user interface (Frame, etc.), we won't discuss it in detail at this point. This program is provided simply to alert you to the possible dual nature of applet programs.
 

/*Applet program hello4.java
This program illustrates that simple applets can run
in a standalone mode as well as inside a browser or
under the AppletViewer program.

This is a Java applet which produces the same output as 
the applet named hello3, except that this program is
capable of running either under AppletViewer or 
standalone.

A main method is provided to support the running of the
applet in the standalone mode.

This program was tested using JDK 1.1.3 under Win95
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class hello4 extends Applet {
  public void paint(Graphics screen) {
    screen.drawString("Hello World",50,25);
  }//end paint()
  
  //Provide a main method that can be used to run the
  // applet in a standalone mode.  
  public static void main(String[] args){
    //Create a Frame for the applet to run in
    Frame myFrame = new Frame(
                          "Copyright 1997, R.G.Baldwin");
    myFrame.setSize(300,100);
    //Instantiate a hello4 applet object.
    Applet myApplet = new hello4();
    //Add the applet object to the Frame object    
    myFrame.add(myApplet);
    //Make the whole thing visible    
    myFrame.setVisible(true);
    
    //This code will terminate the program when the
    // user clicks the close button on the Frame
    myFrame.addWindowListener(new WindowAdapter(){
             public void windowClosing(WindowEvent e){
                                      System.exit(0);}});
  }//end main
} //End hello4 class.

The following html file can be used to run this program under the AppletViewer program.
 

<HTML>
<HEAD>
<title>Hello World Applet</title>
</HEAD>
<BODY>

<applet code="hello4.class" width=300 height=100>
</applet>
</BODY>
</HTML>

Review Questions for Lesson 18

Q - Applets are designed to be executed in a stand-alone mode: True or False?

A - False. Applets are designed to be downloaded and executed on-line under control of a browser.

Q - The overall functionality of applets is restricted relative to applications: True or False?

A - True. Because applets are designed to be downloaded and executed on-line, special security procedures are implemented and applet functionality is restricted in an attempt to prevent downloaded applets from damaging your computer or your data.

Q - Both applications and applets require a main method to be defined in the controlling class: True or False?

A - False. An Applet does not require a main method.

Q - In Java, new classes can be defined by extending existing classes. This is an example of encapsulation, inheritance, or polymorphism - pick one.

A - Inheritance

Q - When a new class extends an existing class, all the variables and methods that are members of the immediate superclass (but none of its ancestors) become members of the new subclass: True or False?

A - False. When a new class extends an existing class, all the variables and methods which are members of the superclass (and which are members of all the ancestors of the superclass) become members of the new subclass.

Q - In the event that the behavior specified by a method of a superclass is not appropriate for objects of the new type defined by the subclass, it is possible to rewrite the method in the subclass to cause it to impart different behavior for objects of the subclass type. What is the common name for this process, and is it more closely associated with encapsulation, inheritance, or polymorphism.

A - The common name is method overriding (as distinguished from method overloading). The result of method overriding is runtime polymoprhism.

Q - All that is required to override a method in Java is to use the same name, modify the method signature in the subclass and then provide a different body for the method: True or False?

A - False: All that is required to override a method in Java is to use the same method signature (which includes the name and the argument list) in the subclass and then provide a different body for the method.

Q - In Java, all classes automatically derive from a superclass named Object: True or False?

A - False. In Java, all classes automatically derive from a superclass named Object or from a direct or indirect subclass of Object. That is to say, all classes in Java form a hierarchical pyramid with the Object class at the top of the pyramid.

Q - The Object class is prohibited from defining methods to be inherited by direct and indirect subclasses: True or False?

A - False: The Object class defines a number of methods that are inherited by and are available to all direct or indirect subclasses of the Object class.

Q - To write an applet, you need to extend Object: True or False?

A - False. To write an applet, you need to extend the Applet class.

Q - Whenever you define a new class, it is a subclass of Object by default: True or False?

A - True

Q - In Java, you can either use inherited methods as is, or you can modify their behavior to better suit the needs of your new types: True or False?

A - True

Q - Modifying inherited methods to make them more suitable for the new types that you define is commonly known as overloading methods: True or False?

A - False. This is commonly known as overriding methods. Overloading methods is something entirely different.

Q - Name two different ways to execute a Java applet.

A - Run it under control of a Java-compatible browser program, or run it under control of the AppletViewer program which is a standard part of the JDK.

Q - Running an applet under a browser requires the use of an HTML file, but no such file is required to use the AppletViewer program: True or False?

A - False. In both cases, it is necessary to produce an HTML file containing tags that reference the applet.

Q - Write an applet and an associated HTML file that displays your name on the screen. Do not use import statements.

A - The applet follows:

/*Applet program Name02.java
This is a Java applet that displays a name.
*/

public class Name02 extends java.applet.Applet {
  //override the paint method
  public void paint(java.awt.Graphics screen) { 
    screen.drawString("Dick Baldwin",50,25);
  }//end overridden paint() method
} //End Name02 class.

The HTML file follows:

<HTML>
<HEAD>
<title>Name Display Applet</title>
</HEAD>
<BODY>
<applet code="Name02.class" width=300 height=100>
</applet>
</BODY>
</HTML>

Q - Import statements are an absolute requirement for any Java program that needs classes which are not automatically imported when a program is compiled: True or False?

A - False: import statements are a convenience to the programmer making it possible to refer to the classes without the requirement to provide a fully qualified name for every class.

Q - As an alternative to importing individual classes, you can import entire packages using a wildcard character: True or False?

A - True. You can import entire packages using statements such as

import java.applet.*;

Q - Importing entire packages will cause the application or applet to execute more slowly: True or False?

A - False. This may slow down compilation but will have no detrimental impact at runtime.

Q - All classes are in packages, either the package specified when the class is defined, or in the default package: True or False?

A - True

Q - All of the classes within a package must use fully qualified names to refer to each other: True or False?

A - False: All of the classes within a package can refer to each other without using fully qualified names.

Q - Every applet must inherit a subclass from the Applet class by extending the Applet class: True or False?

A - True

Q - The subclass of the Applet class need not be defined as public: True or False?

A - False: The subclass of the Applet class must be defined as public.

Q - Instead of having a main method, Applets may override one of the following methods: True or False?

A - True. Applets do not need a main method. However, they must override at least one of the following methods:

Q - init, start and paint are all methods of the Applet class: True or False?

A - False. init and start are methods of the Applet class. paint is a method of the component class that is inherited by several intermediate classes and is finally inherited by the Applet class.

Q - To download an applet from a Web site to a client computer, you use the HTML <APPLET> tag to specify the location of the applet subclass and the dimensions of the onscreen display area: True or False?

A - True

Q - When the <APPLET> tag is encountered by a Java-capable browser, it reserves screen space, loads the specified subclass file onto the computer, and instantiates an object of the subclass. It then invokes one of the three methods listed above for the object causing the Applet to execute: True or False?

A - True

Q - Write a Java application that meets the following specifications:
 

/*Applet program SampProg03.java from lesson 18
Copyright 1997, R.G.Baldwin
Without reviewing the following solution, write a 
Java applet that will display your name in a small 
rectangle within a browser. Write a corresponding 
html file and run the applet from within a browser.
**********************************************************/
import java.applet.Applet;
import java.awt.Graphics;

public class SampProg03 extends Applet {
  public void paint(Graphics screen) {
    screen.drawString("Dick Baldwin",50,25);
  }
} //End SampProg03 class.

-end-