#### Archived

This topic is now archived and is closed to further replies.

# [java] Java is looping my applet?

This topic is 6297 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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!

##### Share on other sites
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.

##### Share on other sites
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.

1. 1
2. 2
3. 3
Rutin
24
4. 4
JoeJ
18
5. 5

• 14
• 23
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631766
• Total Posts
3002228
×