## CPSC 124 (Fall 1998): Lab 5 Using Objects

IN THE FIFTH LAB for Computer Science 124, you will do two fairly short programming exercises in which you create and use objects. In a third exercise, you will learn about "mouse events" and how to make an applet respond to movements of the mouse.

Before you begin, copy the folder /home/cs124/lab5 into your home directory.

The exercises at the end of the lab are due in class on the Monday following the lab.

### Mathematical Functions

In this lab, you will create and use objects based on existing classes. (Next week, you will write your own class from scratch.) The ability to use existing classes is important, since it lets you build on previous work. Furthermore, its lets you work with objects on a black-box basis, without understanding the implementation details inside the box.

For the first exercise of the lab, you will work with mathematical functions of the variable x. A function of x is an object in the real world (the abstract, mathematical part of the real world), and it can be represented as a software object in a program. I have written the class Expr to represent such functions. The compiled class is in the file Expr.class in your lab5 directory, so you can use this class in a program.

An Expr object can be constructed from a String that contains the definition of the function. The String must be a legal mathematical expression, which can contain numbers; the variable x; operators +, -, *, /, and ^; parentheses; and the functions sin, cos, tan, sec, csc, cot, exp, ln, abs, and sqrt. For example, the following strings are legal expressions:

```             "x^2 + x + 1"
"sin(3*x)"
"(2*x - 1) / (3*x + 1)"
"exp(x^2) / exp(tan(x))"
```

(The operator ^ represents raising to a power. The function ln is the natural logarithm function. Abs represents the absolute value function. The trigonometric functions work with radians, not degrees. A function must always be followed by a parameter in parentheses.)

When you construct an object of type Expr with the new operator, you must specify the String that defines the function as an argument to the constructor. For example, you could say

```            Expr func;
func = new Expr("sin(3*x)");
```

The String can, of course, be given by a variable instead of by a literal string: "func = new Expr(def);", where def is a variable of type String.

When the Expr constuctor is called and an error is found in the string, an IllegalArgumentException is thrown. This exception will crash the program unless it is caught and handled in a try statement. Here is how you could catch and handle the error:

```             try {
func = new Expr(def);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
... // do something to handle the error?
}
```

(The variable e contains information about the error that has been caught. In particular, e.getMessage() is an error message.)

Once an Expr object, func, has been created, you can call the method func.value(num) to evaluate the function at a given value of the variable x. The parameter to this method is a double number giving the value of the variable x. The method returns a double number that is the value of the function at the given value of x.

For your first exercise of the lab, write a complete program that reads in the definition of a function of x from the user. You can use TextIO.getln() to read the definition. (If the user types in an illegal definition, keep trying until the user gets it right.) Use this definition to create an Expr object. Then get values of x from the user and print the value of the function for each value of x that the user enters.

Here is an applet that does the same thing that your program is supposed to do. Try out the applet to see how it should work:

### Back to Bouncing Balls

Your lab5 directory contains a file, BouncingBallsApplet.java, that defines an applet that shows a red ball bouncing around on a black background. The ball is an object belonging to the class BouncingBall, which is defined in the file BouncingBall.java. This is, of course, very similar to the bouncing ball applet from Lab 3, except that the variables that record the state of the ball and the subroutines that implement its behaviors have been encapsulated inside a class.

For the second exercise in the lab, you should add at least four more balls to the applet. The balls should be of different colors and sizes. Read the comments in the BouncingBall.java file if you need more information about how to use the constructor and methods in the BouncingBall class.

You can see a completed bouncing ball applet on a separate page.

### Handling MouseDrag Events

The BouncingBall class includes a method headTowards(x,y) that makes the ball head in the direction of the point (x,y). In the third exercise of the lab, you will use this method to make all the balls in your bouncing balls applet move towards the mouse whenever the user holds down the mouse button and moves the mouse on the applet. To do this, you have to listen for the events that are produced when the user drags the mouse, and respond to those events when they occur. There are four steps you have to take to do this.

Step 1. Events in Java are objects. Event objects belong to classes that are defined in the package java.awt.event. To get access to the classes in this package, you should add the line "import java.awt.event.*;" to the beginning of your BouncingBallsApplet.java file. This goes right before or after the line "import java.awt.*;", which is already there.

Step 2. A class that is going to handle mouse drag events should implement an interface called MouseMotionListener. (Interfaces are discussed in Section 4.3 of the text.) This just means that you should add "implements MouseMotionListener" to the first line of the class definition:

```    public class BouncingBallsApplet
extends SimpleAnimationApplet implements MouseMotionListener {
```

Step 3. You have to tell the applet where to send mouse motion events when they occur. You can do this by adding the line "addMouseMotionListener(this);" to the applet's init() method. (The word "this", referring to the applet, means that mouse motion events will be sent from the applet back to this applet itself. See Section 4.2 for a discussion of the special variable "this".)

Step 4. When an applet says that it "implements MouseMotionListener", it makes a promise to define two methods:

```               public void mouseDragged(MouseEvent evt)
and
public void mouseMoved(MouseEvent evt)
```

Add definitions for both of these methods to your applet. The mouseMoved method is called when the user moves the mouse without pressing any button. In the bouncing balls applet, you can leave this method empty. (Use just a pair of braces, { }, for the definition.) You have to include the method, even though it is empty, because it is part of the MouseMotionListener interface. The mouseDragged method is called when the user holds down a button and moves the mouse. You have to define this method so that it makes all the balls head towards the current position of the mouse. The current mouse position can be obtained from the parameter, evt:

```              int x = evt.getX();
int y = evt.getY();
```

Once you have these coordinates, you can call the headTowards() method for each of the balls. For example, to make the red ball head towards the mouse, you would just call

```              redBall.headTowards(x,y);
```

Once you've completed all these steps, your applet should be complete. Try it out! Copy the html file, bounce.html to your www directory, along with the relevant class files, BouncingBallApplet.class and BouncingBall.class. (You also need SimpleAnimationApplet.class, but that should already be in your www directory from previous labs. If not, copy it too.) Put a link on your index page to bounce.html.

### Exercises to Turn in

Exercise 1. Turn in a printout of your first exercise, which is a program to ask the user to enter a mathematical function, f(x), and then to print the value of f(x) for various values of x specified by the user.

Exercises 2 and 3. Turn in a printout of your completed BouncingBallsApplet.java file. The second exercise is to make your applet show at least five bouncing balls, in various colors and sizes. The third exercise is to make the balls head towards the mouse when the mouse is dragged on the applet. Also, post your applet on the Web, and tell me its URL so that I can find it easily.

Exercise 4. Write a short essay comparing the "Bouncing Balls" exercises from Lab 3 with the "Bouncing Balls" exercise in this lab. Explain the advantages of using objects.

Exercise 5. You have now worked with both keyboard events and mouse events. Write a short essay explaining what is meant by an "event" and in particular what it means to say that events are "asynchronous." (See Section 1.1 of the text.) Although objects and events are very different things, they work naturally together. Try to explain why this is true. (Hint: Think in terms of "states" and "messages.")

[ Lab Index | Online Notes ]