Drawing the Fish


The drawFishImage method draws the fish when needed in the memory-based image before that image is flashed onto the screen. This method is passed the Graphics object it should use to draw the fish.

Drawing the image isn't hard; all you need to do is to use the Graphics object's drawImage method to draw the fish at its position as given by its location object. The only subtlety here is that you should draw the image of the fish going to the left if its x velocity is negative, and going to the right if its x velocity is positive. Here's what it looks like in the drawFishImage method:

 public void drawFishImage(Graphics g) {     if(velocity.x < 0) {         g.drawImage(image1, location.x, location.y, tank);     }     else {         g.drawImage(image2, location.x, location.y, tank);     } } 

That completes the entire Aquarium application, and it's ready to roll.

NOTE

Download the complete source code for the Aquarium project, Aquarium.java, at the Sams website. All you need to do is to compile it as discussed next and run it to get it going.


If you're using Java 1.5, which you can get from http://java.sun.com, compile this application, as follows, using the Java compiler, javac, to create the Aquarium.class file that you'll actually run:

CAUTION

If javac isn't in your path, you'll have to preface it with the correct pathsomething like c:\jdk1.5\bin\javac in Windows.


 %javac Aquarium.java 

Then make sure the needed image files (bubble.gif, fish1.gif, and fish2.gif) are in the same directory as Aquarium.class and run the application this way (preface the java command with the correct path, if needed):

 %java Aquarium 

The results appear in Figure 1.1. If you're using Java 1.4, follow the same steps, but make sure you've changed the line

 Vector<Fish> fishes = new Vector<Fish>(); 

at the beginning of the code, to this:

 Vector fishes = new Vector(); 



    Java After Hours(c) 10 Projects You'll Never Do at Work
    Java After Hours: 10 Projects Youll Never Do at Work
    ISBN: 0672327473
    EAN: 2147483647
    Year: 2006
    Pages: 128

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net