[java] Java is looping my applet?

Started by
1 comment, last by capn_midnight 22 years, 12 months ago
I''ve just started with Java, though I''ve been coding C/C++ for about 2 years and java-script for about 5, so I am very familiar with the syntax. I wrote this simple applet the other day, and it did something completely unexpected (or atleast I didn''t expect it)
  
public JavaAp3 extends Applet
{
   public paint(Graphics g)
   {
      int x,n,m;
      Image img;
      img=getImage(getCodeBase(),"knight.gif");
      x=(int)(Math.random*25);
      while(x>=0){
         n=(int)(Math.random*200);
         m=(int)(Math.random*200);
         g.drawImage(img,n,m,this);
         x--;
      }
   }
}
  
Now, I thought this would run once and I would have a random number of knights at random locations on the screen. But instead, it continues to rerun the applet over and over again, so that I have a random number of knights constantly blinking on the screen over and over again. Can I make it stop? How can I take advantage of this? Is there a faster way of putting stuff on screen (this is almost as slow as java-script)? Are you even trying to be intelligent? ''cuz if you are, it ain''t workin'' Down with Tiberia!

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

Advertisement
ok...paint() is called whenever the applet needs to be repainted, this could be due to many operations, mouse moving over something, minimize, maximize browser, yadda yadda yadda. The reason why you get that blinking effect is because you choose a different random number everytime it needs to be repainted. If you want it done only once...then have the random number initialized in the init() method of the applet and put it in a global variable. Then just use that same number in the paint method.
You also don''t want to be retrieving the image everytime in the paint method. This is slow because paint is called very often. Put the getimage and other initialization in the init() method of the applet.

This topic is closed to new replies.

Advertisement