Chapter1.Making Fish Swim in the Multithreaded Aquarium


Chapter 1. Making Fish Swim in the Multithreaded Aquarium

The Aquarium application.

This first project is purely for funa working, multithreaded aquarium where the fish actually swim around and bounce off the walls. We're going to create a dozen fish objects and turn them loose in the aquarium, where they're going to do their own thing as you'd expect fish to do.

You can see what the aquarium looks like in Figure 1.1; although you can't see the colors in the figure, the dozen fish are bright green and swimming at much the same speed that real fish would. When they hit the edge of the aquarium, they reverse direction, and every so often, they change their velocity at random to keep everything lively. The only thing they don't do is need to be fed.

Figure 1.1. Fish swimming in the aquarium.


This application makes a soothing backdrop as the fish wander around, swimming leisurely. You can tweak their speed and how often they change direction in the code, as well as make the aquarium larger or smaller to fit your taste. You can even use your own background image (imagine your boss's face there).

This application contains a certain amount of sophistication, despite its apparent simplicity; the fish are drawn as multithreaded sprites, each of which is its own object that knows how to move and draw itself. Here are some of the things this application does:

  • Creates a sprite class (called Fish) whose objects can move and draw themselves on the screen as needed

  • Animates the sprites, moving them around and bouncing them off the walls when they get too close to the edges

  • Uses double buffering to avoid making the onscreen image flicker

  • Uses a separate thread to move the sprites around

So how do you create this application? First, you've got to build the aquarium to give the fish a home.



    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