Array of Objects Name: _____________________________________________________ Period: _______ Date: _______________________ Lab 08: Racing Cars

advertisement
Topic: Array of Objects
Lab 08: Racing Cars
w/ KeyListener Interface
Objectives
Name: _____________________________________________________
Period: _______ Date: _______________________



I will implement the KeyListener interface.
I will be able to create a Car class.
I will be able maintain an array of Cars.
Car class
Instance variables
Constructor
Methods





myXcord, myYcord,
myNumber, myColor
myLength
mySpeed
iAmSelected
public Car (int x, int y, int length)
 create random number
 create random speed
 create random color
Methods
 draw(Graphics g)
 move()
 increaseSpeed()
 decreaseSpeed()
 selectCar(boolean selected)
CarPanel
Create an array of 3 Cars cars:
Car [ ] cars = new Car[3];
KeyListener interface
public class CarPanel extends JPanel implements KeyListener



ToDo:
Car class
public void keyTyped(KeyEvent e)
public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)
ToDo:
1. Add a 2nd wheel to your car.
2. The car wheel is currently a black circle. Add an inner part which is gray. Then add a
black hub (small black circle in the middle).
3. Add a method increaseSpeed() which will increment mySpeed by 1.
4. Add a method decreaseSpeed() which will decrement mySpeed by 1.
5. The boolean field: iAmSelected, is set when this car has been selected by the Panel.
We need to indicate to the user which car is currently selected. If the field is set to
true, your car’s number should be white. When false, it should be black.
6. Make the number random between 10 and 99.
CarPanel class
ToDo:
 Look at displayKeyInfo() for what type of info is displayed.
 Where do we register the frame/panel for the KeyListener events?
7. Note how the car is selected so that we can increase or decrease it’s speed. If a
number key is typed within your range of cars, the gSelectedCar field is set to the
corresponding index. The corresponding Car object’s selectCar() method is called to
set the internal variable, iAmSelected. This field is used to set the color of the car’s
number.
8. If the up-arrow is pressed, call the increaseSpeed() method of your gSelectedCar.
Look at the console data when keyPressed() is called to determine the keyCode for
the up and down arrow keys. Note: gSelectedCar is the index into the array;
myObjects.
9. If the down-arrow is pressed, call the decreaseSpeed() method of your gSelectedCar.
Make it Better!
Download