CS 201 - Computer Science I - Fall 2002
Lab 4
Loyola College >
Department of Computer Science >
CS 201 >
Labs >
Lab 4
Due
Wednesday, November 6 at 11:59pm
Purpose
This lab uses event listeners, if statements, and methods from the
Math class.
Introduction
Read chapter 6 before doing this lab.
The applet given below changes its background or foreground (text) color
when you click one of the buttons. There are three new topics that
must be introduced before you can write this applet.
Hold Control and click the reload icon if this applet does not work
Event Listeners
When the user interacts with an interface component, that component fires
an event. We can set things up so that when components fire
events, other objects respond to the events by executing certain methods.
Those responding objects are called listeners.
Different components fire different kinds of events. Buttons,
for example, fire ActionEvents. An object that listens for
ActionEvents is called an ActionListener. When an action
listener "hears" an event, it executes its actionPerformed method.
The actionPerformed method should then contain the statements you
want executed when the user clicks a button.
In order to set this up in Java, we need to do several things.
- We need to tell the compiler we are going to use events by
importing the java.awt.event package.
- We need to tell the compiler which objects can act as listeners
by adding "implements XXXListener" to the end of the line
that gives the name of the class defining those listeners
(replace XXX with the kind of event).
- Components need to be told what objects listen for events sent
from them. To tell a component about a listener, one must use an
addXXXListener method.
The parameter to addXXXListener is the listener.
- The listener classes must have the appropriate method written
for them. That method will take an XXXEvent as its
parameter.
if statements
An if statement allows sequences of statements to be executed or
skipped depending on the outcome of a test. The general form is
if (condition)
{
// statements to execute if condition is true
}
else
{
// statements to execute if condition is false
}
condition must be an expression that results in a boolean
value, for example, one that uses the comparison operators <,
>, ==, <=, >= and !=.
The else case is optional. The braces are also optional if there is
only a single statement in each case.
When execution gets to the beginning of the if, the condition
is evaluated. If the condition is true, then the statements after the
if are executed and the statements following
the else are skipped. If the condition is false, then the
statements after the if are skipped and the statements after the
else are executed.
For example, assume that grade was declared as an int
and warning was declared as a String. Then the
following piece of code sets the String to "Failure" if
the value stored in grade is less than 60. Otherwise, it sets the
String to "None".
if (grade < 60)
{
warning = "Failure";
}
else
{
warning = "None";
}
The Math class and random numbers
Most methods ask about the state of an object or change the state of an
object. In either case, in order to use the method we need to specify
which object we need to work with by putting its name in front of the
method's (with . in between).
Methods that don't have anything to do with the state of an object can
be declared as static methods. Mathematical functions are
a good example of these: in order to compute a sine or cosine, you don't need
to know anything about objects. Java supplies a Math class that
contains a lot of these functions. To call a static function
one gives the name of the class where the name of an object would
normally go. For example, Math.sin(0.0) will return the sine
of 0 radians.
Math supplies a method called random that returns a
random double in the range [0.0, 1.0) (the '[' means that the
lower endpoint is included; ')' means that the upper endpoint is not).
We can use this method to obtain random int in any desired range
by multiplying the result of Math.random() to scale it to the
desired range and then truncating it with the (int) type conversion
operator. For example, (int)(Math.random() * 10) gives
a random int between 0 and 9 inclusive (Math.random() gives
a number in [0.0, 1.0), multiplying by 10 gives a number in [0.0, 10.0),
and truncating gives an integer in [0, 9]).
Assignment
Implement the applet given above as a class called Lab4 by
following the steps lsited below.
- Create an applet that contains two Buttons.
The default FlowLayout will be just fine. You should declare
the Buttons as instance variables instead of local variables
in init.
- Declare the Lab4 class as an ActionListener.
Be sure to import the java.awt.event package. You will
have to write an actionPerformed method for your class.
actionPerformed takes an ActionEvent object as
its parameter and returns void. You can leave the body
of actionPerformed empty for now. Make sure that your
code compiles without errors at this point.
- Tell the Buttons that they should send their events to
the applet by passing this to their addActionListener
methods. (Methods are written from the point of view of the
recipient of messages. If the recipient needs to tell something
else about itself [here the applet needs to tell the
components about itself], it can get its address from this).
At this point you should put a System.out.println statement
in actionPerformed. When you run the applet, you should see
the result of the System.out.println every time you click
one of the buttons.
- Create a randomly selected color in actionPerformed. To do
this, you will need to use Math.random to generate
three random integers in the range
0 to 255 inclusive. You can then create a Color object,
passing those three numbers to its constructor. Use
setBackground to change the background of the applet to
that color. If you run your applet at this point, the background
color should change every time you click either button. In the
final step you will change things so that background or foreground
color changes depending on which button you clicked.
- Add an if statement so that you call setBackground
if the "Background" button was clicked to tell the applet
to change its background, and you call
setForegound twice if the "Foreground" button was clicked
to tell the buttons to change their foreground colors. There
are two ways to determine which button was clicked. Both
use the ActionEvent object that is passed into
actionPerformed: 1) use the getSource method
to ask the ActionEvent object which component fired it and
use == to comare the result to one of your buttons;
2) use the getActionCommand method to ask the
ActionEvent method what text was on the button that
fired it and use the equals method to compare that to
"Background" or "Foreground". After adding
this code, your applet should work just like the one given above.
Submissions
Submit your lab by attaching
the file containing your final Java source code to an e-mail
message sent to
jglenn@cs.loyola.edu.