0

I'm trying to run basic animations, and all of the problems in my program is rooted in one of my loops running twice instead of once. I've isolated the problem here:

    import java.awt.*;
    import java.applet.*;
    public class PrinnyTest extends Applet{
public void init()
{
    setSize(600, 550);
}

public void paint (Graphics g)
{
    Image img = getImage(getDocumentBase(), "http://www.clipartqueen.com/image-files/cats-head.png");
    for(int y = 600;y>=20; y--)
    {
        g.setColor(Color.white);
        g.fillRect(0, 0, 600, 550);
        g.drawImage(img, 40, y, null);
        try
        {
            Thread.sleep(20);
        }
        catch(InterruptedException ie)
        {}
    }
}
}

As you can see, it moves the image to the top but then resets the position and starts the loop over again. I feel like the answer is staring me right in the face, but for some reason I can't figure it out. Any help would be greatly appreciated.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jmat
  • 1
  • 1
    `Thread.sleep()` in Event Dispatch Thread isn't recommended. Use swing `javax.swing.Timer` or something like that. – zakki Oct 31 '16 at 08:22
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT components in favor of Swing. .. – Andrew Thompson Oct 31 '16 at 13:14
  • .. 3) See [Java Plugin support deprecated](http://www.gizmodo.com.au/2016/01/rest-in-hell-java-plug-in/) and [Moving to a Plugin-Free Web](https://blogs.oracle.com/java-platform-group/entry/moving_to_a_plugin_free). – Andrew Thompson Oct 31 '16 at 13:14
  • 1
    General tips: 1) Never try to load resources (such as images) within a paint method! Such image loading should be done in the `init()` method. 2) Remove `setSize(600, 550);` from the `init()` method. The applet's size is set by the HTML that loads it. The applet should not try to 2nd guess the space it has been provided. 3) `g.drawImage(img, 40, y, null);` should be `g.drawImage(img, 40, y, this);` since an `Applet` implements `ImageObserver`. 4) `g.setColor(Color.white); g.fillRect(0, 0, 600, 550);` would better be achieved by setting the BG color to white in the constructor, then.. – Andrew Thompson Oct 31 '16 at 13:19
  • .. calling `super.paint(g);` as the first thing in the overriden paint method. 5) Always use `@Override` notation when changing methods, as it provides compile time checking of method signatures. 6) And like mentioned by @zakki earlier, don't ever call for a `Thread.sleep(..)` in a paint method. This is not the correct way to go about animation. – Andrew Thompson Oct 31 '16 at 13:22

0 Answers0