开发者

How to delay between drawings in a Java Applet

I'm writing a program to input a number and draw that number of circles of random color and location on an applet. I've been up all night trying to figure out how to add a delay between each of the circles appearing. Right now if I have a for-each statement with a delay in it, and say I input 20 circles and have a delay of 1000, it won't do anything for 20 seconds, then all the circles will appe开发者_如何学Goar at once, because the screen doesn't get refreshed until the end of the paint() method.

The only other alternative I could think of was to have a for-each statement in the start() method that would add a color and coordinate to an array, and have the paint() method draw all the circles in this array. I could be wrong, but I would imagine that this would use up way too much memory.

Another possibility would be to just add a circle on to the existing frame without clearing it, but I couldn't find a way to do this.


Use a javax.swing.Timer to add a new Circle object to an expandable list such as an ArrayList. Call repaint() after each addition. In paintComponent(Graphics) draw every Circle in the list.


Update

Unfortunately I cannot add comments at the moment (see External JS failed to load for the gory details). For that reason, I'm adding this as an edit.

@mKorbel: No I sure have not tried it on 1.6.0_26! If I'd tried it at all, I'd have posted the code. ;)

@Tycho: I did not notice you added the awt tag and presumed you were working with Swing.

Are you really using AWT? (If so.) Why?


@Tycho: "The only thing I could tell by quickly searching was that Swing is used more for user interfaces, which is not what I'm going for here."

Umm.. both AWT and Swing (using Applet/JApplet or Frame/JFrame) are used for developing Graphical User Interfaces. Or to put that another way, whether using AWT or Swing, or developing an applet or free-floating frame, you are developing a (G)UI.

Either the applet extends java.applet.Applet (AWT) or javax.swing.JApplet (Swing).

If your applet extends Applet, change it to a Swing JApplet. Few GUI developers can even remember AWT well enough to give good advice on it. My advice was all related to JApplet/Swing. It would not work using AWT.


Use a timer. For example, when you start drawing your circles, set a value:

   time_press = System.currentTimeMillis();
   circles_to_draw = 20;

Then somewhere in your draw method, do the following:

while(circles_to_draw > 0 && System.currentTimeMillis() < time_press + 1000)
{
    time_press += 1000;
    circles_to_draw --;

    //Draw your circle
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜