CS 178 Programming with Multimedia Objects

Fall 2004

Recitation Exercise

Prepared by: Aditya Mathur.

For use in class on Dec 3, 2004.

Learning objectives:
  • Creating and using a Thread for animation.
  • Programming a simple game.

Exercise:

1. Examine the applet given at the end of this page. Write a ButtonFun applet that has the same set of buttons and textwidgets as the applet. The applet implements Runnable and ActionListener.

Note that the buttons that change their label and colors are to be declared as an array of 4 buttons. Declare an array of four labels and initialize the elements of this array to "one," "two," "three,"and "four," respectively. Declare curentlyActive as an int and set it to 0 indicating that the leftmost button is active initially. Declare score and numClicks to be integers and initalize to 0. Declare refreshRate as an integer and set it to 70.

Declare an object named anim of type Thread.

2. Write the init() method to create the applet panel as shown. Try t keep the placement similar to the applet shown. Its size is 500 (width) and 200 (height).

3. Write the start() method. Create a new thread and start it.

4. Write the run() method. This method has an infinite loop that does the following: (a) Sets the label of the currently active button to an empty string and its color to white, (b) increments currentlyActive by 1 modulo 4, (c) sets the text of the currently active button to a suitable label (i.e. "one", "two", etc.) and its background color to blue, and (d) make the thread go to sleep for a time equal to refreshRate.

5. Write the actionPerformed method. This method proceses each of the button clicks. Note that when the currently active button is clicked the score is incremented. numClicks is implemented when any of the four buttons is clicked.

Code (ButtonFun)

Last update: November 19, 2004