next up previous
Next: About this document ... Up: In the Laboratory: CyberPetApplet Previous: Lab Exercise 6: Adding

Lab Exercise 7: Adding Images to CyberPetApplet (optional)

Download the image files provided for this lab. There are three images: spidereat.gif, spidersleep.gif, and spiderthink.gif. Place them in the same directory as your source code (*.java) files.

Add images to the applet that correspond to CyberPet's three states. Follow the example shown in this chapter. There are two modifications that must be made to that example. First, the paint() method should draw the image that corresponds to CyberPet's current state:

    public void paint(Graphics g)
    {
        String petState = pet1.getState();        // Get pet1's state
        if (petState.equals("Eating"))            // Draw the appropriate image
            g.drawImage(eatImage, 20, 100, this);
        else if ( petState.equals("Sleeping"))
            g.drawImage(sleepImage, 20, 100, this);
        else if ( petState.equals("Thinking"))
            g.drawImage(sleepImage, 20, 100, this);
    }

Finally, it is necessary to repaint() the applet after each button click. To do this you would add the following statement at the end of your actionPerformed() method:

    repaint(); // Call the paint() method

The repaint() method just calls the applet's paint() method. The reason that paint(Graphics) is not called directly here is because it requires a Graphics parameter, which is not directly available to the actionPerformed() method. The repaint() method takes care of getting the applet's Graphics object and passing it to paint(), so the images can be displayed on it.



Ralph Morelli {Faculty}
12/22/1999