SA-5, due Oct 7
This assignment gives you practice creating listeners to animate an applet.
Assignment
Your assignment is to modify a Checkerboard applet from so that whichever square you click on flashes between its normal color and yellow, with the change to or from yellow occurring every half second (i.e., every 500 milliseconds).You can play with my implementation if you like:
Start with the applet Checkerboard.java. This applet draws a checkerboard. You should read it carefully to figure out how it works.
Here are some design ideas that you might find useful. You should
define constants (i.e., final
variables) as appropriate.
As with the ClickAMac
applet from lecture, use an instance variable to remember where the
mouse was clicked; set this instance variable in the
mouseClicked
method.
To implement the flashing behavior, you'll of course need to create a
Timer
object and have the appropriate
actionPerformed
method called every 500 milliseconds.
Figure out a way to know whether or not to paint the yellow square,
and what to do whenever the Timer
rings.
In your paintComponent
method, draw the entire
checkerboard. After you've drawn the checkerboard, if a point has
been clicked, and if you
should draw the square in yellow where you clicked, do so. There will
be a brief moment after the checkboard is drawn and before the yellow
square is drawn, but it is so brief that nobody will ever notice.
You are free to make inner classes for listeners, to let the applet itself act as a listener, or to let the canvas act as a listener.
Given a Point
—let's say that it's referenced by
clickPoint
—how do we determine the row and column
numbers of the square containing this point? This is pretty easy.
Given that the squares are 30 pixels in each dimension, the row number
is clickPoint.y / 30
and the column number is
clickPoint.x / 30
. There are a couple of things to note:
- We naturally think of (x, y) and
row/column—that is, first x, then y, and
first row, then column. But notice that the row depends on
y, not on x. And the column depends on
x, not on y. So be careful here.
- I wrote
30
in the expressions above because that's the square size. You will not write30
. You will use a constant.
Blackboard submission
Submit via Blackboard the zip file of a folder that contains the following two files: (1) YourCheckerboard.java
, and (2) a screenshot of your checkerboard with a yellow square.