CIS 180 - Lab 1
Editing, Compiling, and Running an Applet



FirstApplet Example



In the Laboratory: Editing, Compiling, and Running an Applet

The purpose of this first laboratory project is to give you some hands-on experience editing and compiling a Java program. This will not only familiarize you with the software that will be used in your course but will also elaborate on some of the concepts introduced in this chapter. The objectives of this exercise are

Don't worry that you won't understand all of the Java code in the applet. We'll eventually get to language details in subsequent chapters.

This applet plays a silly game with the user. Every time the user clicks on the button labeled ``Click Me Not!'' the applet button's label changes to ``Click Me!'' and vice versa.

Program Walkthrough: Program Style and Documentation

FirstApplet's complete source code is shown here.
/**
* File: FirstApplet.java
* Author: Java Java Java
* Description: This applet plays the click-me-not game with the user.
*/

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

/*
* The FirstApplet class plays the click-me-not game with the user.
* @author Java Java Java
*/

public class FirstApplet extends Applet implements ActionListener
{
private Button clickMe; // Declare the button

/**
* The init() method initializes the applet.
*/
public void init()
{
clickMe = new Button("Click Me Not!"); // Create the button
clickMe.addActionListener(this); // Activate the button
add(clickMe); // Add it to the applet
} // init()

/**
* The actionPerformed() method is called whenever the button is clicked.
*/
public void actionPerformed (ActionEvent e)
{
if (clickMe.getLabel().equals("Click Me!"))
clickMe.setLabel("Click Me Not!");
else
clickMe.setLabel("Click Me!");
} // actionPerformed()
} // End of FirstApplet

The program begins with a comment block, which presents important information about the program, including the name of the file that contains it, the name of the author, and a brief description of what the program does.

Java Language Rule: Comments. A multiline comment begins with ``/*'' and ends with ``*/'' and may extend over several lines. It is ignored by the compiler. A multiline comment that begins with ``/**'' and ends with ``*/'' is called a documentation comment. These kinds of comments can be processed by special software provided by Java that will automatically generate documentation for the class.


Programming Tip: Use of Comments. A well-written program should begin with a comment block that provides the name of the program, its author, and a description of what the program does.

In addition to the comment block at the beginning of FirstApplet and several other comment blocks in the program, there are also several single-line comments used to clarify the code. Commenting your code in this way is an important part of program development. Appendix A lays out the style and documentation guidelines that are followed in this book. In subsequent laboratory projects, as our programs become more sophisticated, we will introduce additional documentation requirements.

Students invariably hate putting comments in their programs. After all, it seems somewhat anticlimactic, having to go back and document your program after you have finished designing, writing, and testing it. The way to avoid the sense of anticlimax is to ``document as you go'' rather than leaving it to the end. In many cases, your design document can serve as the basis for the comments in your program. One of the main reasons for commenting code is so that you, or someone else, will be able to understand the code the next time you have to modify it. Students who go on to be professional programmers often write back with reports that they now understand how important program documentation is. As one of my former students told me,


Lanning's Limerick
All hard-headed coders say ''Phooey,
Putting comments in code is just hooey!''
But when they are asked,
To reread what they hacked,
They discover their programs are screwy.


Program Walkthrough: The import Declaration

The next portion of the program contains the three import statements:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;


The import statement is a convenience that allows you to refer to library classes by their short names rather than by their fully qualified names. For example, the first import statement tells the compiler that in this program we will refer to the java.applet.Applet class simply as Applet. This allows us to write a statement like


public class FirstApplet extends Applet


instead of being required to use the full name for the Applet class


public class FirstApplet extends java.applet.Applet


But either will work. The expression java.awt.* uses the asterisk (``*'') as a wildcard character that matches any public class name in the java.awt package. This allows you to refer to all public classes in the java.awt package--for example, java.awt.Button and java.awt.TextArea--by their short names. The third statement matches all the class names in the java.awt.event package, which allows the program to refer to java.awt.event.Action Listener by its short name.

Program Walkthrough: Class Definition

The next element in the program is the header of the class definition:


public class FirstApplet extends Applet implements ActionListener


This is a more complex class header than the one we used for the HelloWorld or Rectangle classes. But this applet is a more sophisticated program because it interacts with the user. Don't worry at this point if its operations seem a bit magical.

The class header serves the purpose of naming the class FirstApplet, designating its accessibility public, specifying that it is an Applet, and declaring that it implements ActionListener, an interface that allows it to respond to the user's mouse clicks. The header begins the definition of the class, which extends all the way to the last line of the program--the line marked with the //End of FirstApplet comment.

The body of a class definition is a block, as is the body of a method. Note how the statements in the block are indented, and how the braces are aligned and commented. These style conventions serve to make the program more readable.


Programming Tip: Use of Indentation. The code within a block should be indented, and the block's opening and closing braces should be aligned. A comment should be used to mark the end of a block of code.

Following the header is a variable declaration:


private Button clickMe;      // The button


As we will see in more detail in the next chapter, variables are memory locations that can store values. In this case, the Applet object is storing a reference to a Button object.


Programming Tip: Choice of Variable Names. Names chosen for variables, methods, and classes should be descriptive of the element's purpose and should be written in a distinctive style to distinguish them from other elements of the program. For variable and method names, our convention is to start the name with a lowercase letter and use uppercase letters to distinguish words within the name--for example, clickMe. Class names begin with an uppercase letter (FirstApplet).

Program Walkthrough: Method Definition

The next element of the program is the init() method:


public void init()
{
clickMe = new Button("Click Me Not!"); // Create the button
clickMe.addActionListener(this); // Activate the button
add(clickMe); // Add it to the applet
} // init()


The init() method is called once, automatically, whenever an applet is loaded into the Java Virtual Machine. Its purpose is to initialize the applet's interface and any variables used in the applet's processing. As the method's comments indicate, the method creates (new) a Button and adds it to the applet, which causes it to appear on the screen when the applet is run.

The actionPerformed() method is the last element in the program:


public void actionPerformed (ActionEvent e)
{
if (clickMe.getLabel().equals("Click Me!"))
clickMe.setLabel("Click Me Not!");
else
clickMe.setLabel("Click Me!");
} // actionPerformed()


This method is called automatically whenever the applet's button is clicked. Its purpose is to ``perform action'' when a button-click event takes place. In this case the action it takes is to toggle the button's label from ``Click Me!'' to ``Click Me Not!'' or vice versa.

Lab Exercise 1: Editing, Compiling, and Running

Using whatever programming environment you have available in your computing lab, edit, compile, and run the FirstApplet program. However, don't just keyboard the whole program and then compile it. Instead, use the stepwise refinement approach as outlined here.

Hopefully, going through this exercise has illustrated some of the advantages of the stepwise refinement approach to writing Java code.

Download FirstApplet.html file from http://www.cis.umassd.edu/~x2zhang/courses/CIS180/labs/lab1/FirstApplet.html and save it in the same location as the
FirstApplet.class file. Load the FirstApplet.html from a web browser window, the applet should be displayed.


Programming Tip: Stepwise Refinement. Stepwise refinement is a coding and testing strategy that employs the divide-and-conquer principle. Keyboard and test small segments of the program in a step-by-step fashion. In addition to breaking up the task into more manageable subtasks, this approach helps to localize any problems that arise.

Lab Exercise 2: Generating Syntax Errors

In this exercise you will make modifications to FirstApplet which will introduce syntax errors into your program. The main purpose here is to give you a first look at how your programming environment reports error messages. You'll also learn some of the most fundamental rules of Java syntax.

For each of the items below, make the editing change and then recompile the program. Make note of any error messages that are generated by the compiler. Try to understand what the message is telling you, and try to learn from the error, so it will be less likely to occur next time. After you have finished with that error, restore the code to its original form and move on to the next item.

Lab Exercise 3: Generating Semantic Errors

Recall that semantic errors cannot be detected by the compiler. They are errors in the logic of the program that cause it to do something it is not really supposed to do. For each of the following errors, try to think about what will happen before you run the program. Then try to describe the logic error being committed. Ask yourself what kind of test you might perform to detect the error (if you didn't already know where it was).

That's enough! Feel free to make up your own experiments and play around some more with the program.


To Submit: upload your FirstApplet.java file for lab1.